Coverage Report

Created: 2023-11-12 01:18

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ                   https://dearimgui.com/faq
11
// - Getting Started       https://dearimgui.com/getting-started
12
// - Homepage              https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
// - Tests & Automation    https://github.com/ocornut/imgui_test_engine
19
20
// For first-time users having issues compiling/linking/running/loading fonts:
21
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
23
24
// Copyright (c) 2014-2023 Omar Cornut
25
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
26
// See LICENSE.txt for copyright and licensing details (standard MIT License).
27
// This library is free but needs your support to sustain development and maintenance.
28
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
29
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
30
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
31
32
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
33
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
34
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
35
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
36
// to a better solution or official support for them.
37
38
/*
39
40
Index of this file:
41
42
DOCUMENTATION
43
44
- MISSION STATEMENT
45
- CONTROLS GUIDE
46
- PROGRAMMER GUIDE
47
  - READ FIRST
48
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
49
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
50
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
51
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
52
- API BREAKING CHANGES (read me when you update!)
53
- FREQUENTLY ASKED QUESTIONS (FAQ)
54
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
55
56
CODE
57
(search for "[SECTION]" in the code to find them)
58
59
// [SECTION] INCLUDES
60
// [SECTION] FORWARD DECLARATIONS
61
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
62
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
63
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
64
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
65
// [SECTION] MISC HELPERS/UTILITIES (File functions)
66
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
67
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
68
// [SECTION] ImGuiStorage
69
// [SECTION] ImGuiTextFilter
70
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
71
// [SECTION] ImGuiListClipper
72
// [SECTION] STYLING
73
// [SECTION] RENDER HELPERS
74
// [SECTION] INITIALIZATION, SHUTDOWN
75
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
76
// [SECTION] INPUTS
77
// [SECTION] ERROR CHECKING
78
// [SECTION] LAYOUT
79
// [SECTION] SCROLLING
80
// [SECTION] TOOLTIPS
81
// [SECTION] POPUPS
82
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
83
// [SECTION] DRAG AND DROP
84
// [SECTION] LOGGING/CAPTURING
85
// [SECTION] SETTINGS
86
// [SECTION] LOCALIZATION
87
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
88
// [SECTION] DOCKING
89
// [SECTION] PLATFORM DEPENDENT HELPERS
90
// [SECTION] METRICS/DEBUGGER WINDOW
91
// [SECTION] DEBUG LOG WINDOW
92
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
93
94
*/
95
96
//-----------------------------------------------------------------------------
97
// DOCUMENTATION
98
//-----------------------------------------------------------------------------
99
100
/*
101
102
 MISSION STATEMENT
103
 =================
104
105
 - Easy to use to create code-driven and data-driven tools.
106
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
107
 - Easy to hack and improve.
108
 - Minimize setup and maintenance.
109
 - Minimize state storage on user side.
110
 - Minimize state synchronization.
111
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
112
 - Efficient runtime and memory consumption.
113
114
 Designed primarily for developers and content-creators, not the typical end-user!
115
 Some of the current weaknesses (which we aim to address in the future) includes:
116
117
 - Doesn't look fancy.
118
 - Limited layout features, intricate layouts are typically crafted in code.
119
120
121
 CONTROLS GUIDE
122
 ==============
123
124
 - MOUSE CONTROLS
125
   - Mouse wheel:                   Scroll vertically.
126
   - SHIFT+Mouse wheel:             Scroll horizontally.
127
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
128
   - Click ^, Double-Click title:   Collapse window.
129
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
130
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
131
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
132
133
 - TEXT EDITOR
134
   - Hold SHIFT or Drag Mouse:      Select text.
135
   - CTRL+Left/Right:               Word jump.
136
   - CTRL+Shift+Left/Right:         Select words.
137
   - CTRL+A or Double-Click:        Select All.
138
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
139
   - CTRL+Z, CTRL+Y:                Undo, Redo.
140
   - ESCAPE:                        Revert text to its original value.
141
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
142
143
 - KEYBOARD CONTROLS
144
   - Basic:
145
     - Tab, SHIFT+Tab               Cycle through text editable fields.
146
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
147
     - CTRL+Click                   Input text into a Slider or Drag widget.
148
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
149
     - Tab, SHIFT+Tab:              Cycle through every items.
150
     - Arrow keys                   Move through items using directional navigation. Tweak value.
151
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
152
     - Enter                        Activate item (prefer text input when possible).
153
     - Space                        Activate item (prefer tweaking with arrows when possible).
154
     - Escape                       Deactivate item, leave child window, close popup.
155
     - Page Up, Page Down           Previous page, next page.
156
     - Home, End                    Scroll to top, scroll to bottom.
157
     - Alt                          Toggle between scrolling layer and menu layer.
158
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
159
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
160
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
161
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
162
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
163
164
 - GAMEPAD CONTROLS
165
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
166
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
167
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
168
   - Backend support: backend needs to:
169
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
170
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
171
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
172
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
173
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
174
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
175
176
 - REMOTE INPUTS SHARING & MOUSE EMULATION
177
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
178
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
179
     in order to share your PC mouse/keyboard.
180
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
181
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
182
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
183
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
184
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
185
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
186
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
187
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
188
189
190
 PROGRAMMER GUIDE
191
 ================
192
193
 READ FIRST
194
 ----------
195
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
196
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
197
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
198
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
199
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
200
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
201
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
202
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
203
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
204
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
205
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
206
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
207
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
208
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
209
   If you get an assert, read the messages and comments around the assert.
210
 - This codebase aims to be highly optimized:
211
   - A typical idle frame should never call malloc/free.
212
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
213
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
214
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
215
 - This codebase aims to be both highly opinionated and highly flexible:
216
   - This code works because of the things it choose to solve or not solve.
217
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
218
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
219
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
220
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
221
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
222
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
223
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
224
     (so don't use ImVector in your code or at our own risk!).
225
   - Building: We don't use nor mandate a build system for the main library.
226
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
227
     This is also because providing a build system for the main library would be of little-value.
228
     The build problems are almost never coming from the main library but from specific backends.
229
230
231
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
232
 ----------------------------------------------
233
 - Update submodule or copy/overwrite every file.
234
 - About imconfig.h:
235
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
236
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
237
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
238
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
239
240
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
241
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
242
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
243
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
244
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
245
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
246
   likely be a comment about it. Please report any issue to the GitHub page!
247
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
248
 - Try to keep your copy of Dear ImGui reasonably up to date!
249
250
251
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
252
 ---------------------------------------------------------------
253
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
254
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
255
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
256
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
257
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
258
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
259
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
260
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
261
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
262
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
263
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
264
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
265
266
267
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
268
 --------------------------------------
269
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
270
 The sub-folders in examples/ contain examples applications following this structure.
271
272
     // Application init: create a dear imgui context, setup some options, load fonts
273
     ImGui::CreateContext();
274
     ImGuiIO& io = ImGui::GetIO();
275
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
276
     // TODO: Fill optional fields of the io structure later.
277
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
278
279
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
280
     ImGui_ImplWin32_Init(hwnd);
281
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
282
283
     // Application main loop
284
     while (true)
285
     {
286
         // Feed inputs to dear imgui, start new frame
287
         ImGui_ImplDX11_NewFrame();
288
         ImGui_ImplWin32_NewFrame();
289
         ImGui::NewFrame();
290
291
         // Any application code here
292
         ImGui::Text("Hello, world!");
293
294
         // Render dear imgui into screen
295
         ImGui::Render();
296
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
297
         g_pSwapChain->Present(1, 0);
298
     }
299
300
     // Shutdown
301
     ImGui_ImplDX11_Shutdown();
302
     ImGui_ImplWin32_Shutdown();
303
     ImGui::DestroyContext();
304
305
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
306
307
     // Application init: create a dear imgui context, setup some options, load fonts
308
     ImGui::CreateContext();
309
     ImGuiIO& io = ImGui::GetIO();
310
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
311
     // TODO: Fill optional fields of the io structure later.
312
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
313
314
     // Build and load the texture atlas into a texture
315
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
316
     int width, height;
317
     unsigned char* pixels = nullptr;
318
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
319
320
     // At this point you've got the texture data and you need to upload that to your graphic system:
321
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
322
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
323
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
324
     io.Fonts->SetTexID((void*)texture);
325
326
     // Application main loop
327
     while (true)
328
     {
329
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
330
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
331
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
332
        io.DisplaySize.x = 1920.0f;             // set the current display width
333
        io.DisplaySize.y = 1280.0f;             // set the current display height here
334
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
335
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
336
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
337
338
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
339
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
340
        ImGui::NewFrame();
341
342
        // Most of your application code here
343
        ImGui::Text("Hello, world!");
344
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
345
        MyGameRender(); // may use any Dear ImGui functions as well!
346
347
        // Render dear imgui, swap buffers
348
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
349
        ImGui::EndFrame();
350
        ImGui::Render();
351
        ImDrawData* draw_data = ImGui::GetDrawData();
352
        MyImGuiRenderFunction(draw_data);
353
        SwapBuffers();
354
     }
355
356
     // Shutdown
357
     ImGui::DestroyContext();
358
359
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
360
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
361
 Please read the FAQ and example applications for details about this!
362
363
364
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
365
 ---------------------------------------------
366
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
367
368
    void MyImGuiRenderFunction(ImDrawData* draw_data)
369
    {
370
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
371
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
372
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
373
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
374
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
375
       ImVec2 clip_off = draw_data->DisplayPos;
376
       for (int n = 0; n < draw_data->CmdListsCount; n++)
377
       {
378
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
379
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
380
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
381
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
382
          {
383
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
384
             if (pcmd->UserCallback)
385
             {
386
                 pcmd->UserCallback(cmd_list, pcmd);
387
             }
388
             else
389
             {
390
                 // Project scissor/clipping rectangles into framebuffer space
391
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
392
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
393
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
394
                     continue;
395
396
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
397
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
398
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
399
                 // - Clipping coordinates are provided in imgui coordinates space:
400
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
401
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
402
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
403
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
404
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
405
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
406
407
                 // The texture for the draw call is specified by pcmd->GetTexID().
408
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
409
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
410
411
                 // Render 'pcmd->ElemCount/3' indexed triangles.
412
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
413
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
414
             }
415
          }
416
       }
417
    }
418
419
420
 API BREAKING CHANGES
421
 ====================
422
423
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
424
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
425
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
426
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
427
428
(Docking/Viewport Branch)
429
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
430
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
431
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
432
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
433
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
434
435
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
436
                           - old: BeginChild("Name", size, true)
437
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
438
                           - old: BeginChild("Name", size, false)
439
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
440
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
441
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
442
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
443
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
444
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
445
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
446
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
447
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
448
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
449
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
450
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
451
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
452
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
453
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
454
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
455
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
456
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
457
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
458
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
459
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
460
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
461
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
462
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
463
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
464
                           - ListBoxFooter()  -> use EndListBox()
465
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
466
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
467
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
468
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
469
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
470
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
471
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
472
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
473
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
474
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
475
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
476
                         it has been frequently requested by people to use our own. We had an opt-in define which was
477
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
478
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
479
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
480
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
481
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
482
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
483
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
484
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
485
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
486
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
487
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
488
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
489
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
490
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
491
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
492
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
493
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
494
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
495
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
496
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
497
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
498
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
499
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
500
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
501
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
502
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
503
                         - previously this would make the window content size ~200x200:
504
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
505
                         - instead, please submit an item:
506
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
507
                         - alternative:
508
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
509
                         - content size is now only extended when submitting an item!
510
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
511
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
512
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
513
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
514
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
515
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
516
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
517
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
518
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
519
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
520
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
521
                        - Official backends from 1.87+                  -> no issue.
522
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
523
                        - Custom backends not writing to io.NavInputs[] -> no issue.
524
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
525
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
526
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
527
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
528
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
529
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
530
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
531
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
532
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
533
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
534
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
535
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
536
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
537
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
538
                       read https://github.com/ocornut/imgui/issues/4921 for details.
539
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
540
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
541
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
542
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
543
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
544
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
545
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
546
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
547
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
548
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
549
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
550
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
551
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
552
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
553
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
554
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
555
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
556
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
557
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
558
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
559
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
560
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
561
                        - if you are using official backends from the source tree: you have nothing to do.
562
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
563
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
564
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
565
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
566
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
567
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
568
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
569
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
570
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
571
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
572
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
573
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
574
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
575
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
576
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
577
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
578
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
579
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
580
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
581
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
582
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
583
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
584
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
585
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
586
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
587
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
588
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
589
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
590
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
591
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
592
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
593
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
594
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
595
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
596
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
597
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
598
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
599
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
600
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
601
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
602
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
603
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
604
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
605
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
606
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
607
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
608
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
609
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
610
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
611
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
612
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
613
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
614
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
615
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
616
                       - if you omitted the 'power' parameter (likely!), you are not affected.
617
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
618
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
619
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
620
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
621
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
622
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
623
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
624
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
625
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
626
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
627
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
628
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
629
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
630
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
631
                       - ShowTestWindow()                    -> use ShowDemoWindow()
632
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
633
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
634
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
635
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
636
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
637
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
638
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
639
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
640
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
641
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
642
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
643
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
644
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
645
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
646
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
647
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
648
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
649
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
650
                       - ImFont::Glyph                       -> use ImFontGlyph
651
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
652
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
653
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
654
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
655
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
656
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
657
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
658
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
659
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
660
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
661
                       Please reach out if you are affected.
662
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
663
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
664
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
665
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
666
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
667
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
668
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
669
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
670
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
671
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
672
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
673
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
674
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
675
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
676
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
677
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
678
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
679
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
680
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
681
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
682
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
683
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
684
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
685
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
686
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
687
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
688
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
689
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
690
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
691
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
692
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
693
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
694
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
695
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
696
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
697
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
698
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
699
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
700
                       consistent with other functions. Kept redirection functions (will obsolete).
701
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
702
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
703
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
704
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
705
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
706
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
707
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
708
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
709
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
710
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
711
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
712
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
713
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
714
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
715
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
716
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
717
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
718
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
719
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
720
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
721
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
722
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
723
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
724
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
725
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
726
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
727
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
728
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
729
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
730
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
731
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
732
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
733
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
734
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
735
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
736
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
737
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
738
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
739
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
740
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
741
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
742
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
743
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
744
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
745
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
746
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
747
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
748
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
749
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
750
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
751
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
752
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
753
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
754
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
755
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
756
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
757
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
758
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
759
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
760
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
761
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
762
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
763
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
764
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
765
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
766
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
767
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
768
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
769
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
770
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
771
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
772
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
773
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
774
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
775
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
776
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
777
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
778
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
779
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
780
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
781
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
782
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
783
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
784
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
785
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
786
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
787
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
788
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
789
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
790
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
791
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
792
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
793
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
794
                     - the signature of the io.RenderDrawListsFn handler has changed!
795
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
796
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
797
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
798
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
799
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
800
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
801
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
802
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
803
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
804
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
805
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
806
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
807
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
808
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
809
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
810
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
811
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
812
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
813
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
814
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
815
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
816
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
817
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
818
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
819
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
820
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
821
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
822
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
823
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
824
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
825
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
826
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
827
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
828
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
829
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
830
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
831
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
832
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
833
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
834
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
835
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
836
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
837
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
838
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
839
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
840
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
841
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
842
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
843
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
844
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
845
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
846
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
847
848
849
 FREQUENTLY ASKED QUESTIONS (FAQ)
850
 ================================
851
852
 Read all answers online:
853
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
854
 Read all answers locally (with a text editor or ideally a Markdown viewer):
855
   docs/FAQ.md
856
 Some answers are copied down here to facilitate searching in code.
857
858
 Q&A: Basics
859
 ===========
860
861
 Q: Where is the documentation?
862
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
863
    - Run the examples/ applications and explore them.
864
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
865
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
866
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
867
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
868
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
869
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
870
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
871
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
872
    - Your programming IDE is your friend, find the type or function declaration to find comments
873
      associated with it.
874
875
 Q: What is this library called?
876
 Q: Which version should I get?
877
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
878
 >> See https://www.dearimgui.com/faq for details.
879
880
 Q&A: Integration
881
 ================
882
883
 Q: How to get started?
884
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
885
886
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
887
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
888
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
889
890
 Q. How can I enable keyboard or gamepad controls?
891
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
892
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
893
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
894
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
895
 >> See https://www.dearimgui.com/faq
896
897
 Q&A: Usage
898
 ----------
899
900
 Q: About the ID Stack system..
901
   - Why is my widget not reacting when I click on it?
902
   - How can I have widgets with an empty label?
903
   - How can I have multiple widgets with the same label?
904
   - How can I have multiple windows with the same label?
905
 Q: How can I display an image? What is ImTextureID, how does it work?
906
 Q: How can I use my own math types instead of ImVec2?
907
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
908
 Q: How can I display custom shapes? (using low-level ImDrawList API)
909
 >> See https://www.dearimgui.com/faq
910
911
 Q&A: Fonts, Text
912
 ================
913
914
 Q: How should I handle DPI in my application?
915
 Q: How can I load a different font than the default?
916
 Q: How can I easily use icons in my application?
917
 Q: How can I load multiple fonts?
918
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
919
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
920
921
 Q&A: Concerns
922
 =============
923
924
 Q: Who uses Dear ImGui?
925
 Q: Can you create elaborate/serious tools with Dear ImGui?
926
 Q: Can you reskin the look of Dear ImGui?
927
 Q: Why using C++ (as opposed to C)?
928
 >> See https://www.dearimgui.com/faq
929
930
 Q&A: Community
931
 ==============
932
933
 Q: How can I help?
934
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
935
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
936
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
937
      Also see https://github.com/ocornut/imgui/wiki/Sponsors
938
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
939
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
940
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
941
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
942
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
943
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
944
945
*/
946
947
//-------------------------------------------------------------------------
948
// [SECTION] INCLUDES
949
//-------------------------------------------------------------------------
950
951
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
952
#define _CRT_SECURE_NO_WARNINGS
953
#endif
954
955
#ifndef IMGUI_DEFINE_MATH_OPERATORS
956
#define IMGUI_DEFINE_MATH_OPERATORS
957
#endif
958
959
#include "imgui.h"
960
#ifndef IMGUI_DISABLE
961
#include "imgui_internal.h"
962
963
// System includes
964
#include <stdio.h>      // vsnprintf, sscanf, printf
965
#include <stdint.h>     // intptr_t
966
967
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
968
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
969
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
970
#endif
971
972
// [Windows] OS specific includes (optional)
973
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
974
#define IMGUI_DISABLE_WIN32_FUNCTIONS
975
#endif
976
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
977
#ifndef WIN32_LEAN_AND_MEAN
978
#define WIN32_LEAN_AND_MEAN
979
#endif
980
#ifndef NOMINMAX
981
#define NOMINMAX
982
#endif
983
#ifndef __MINGW32__
984
#include <Windows.h>        // _wfopen, OpenClipboard
985
#else
986
#include <windows.h>
987
#endif
988
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
989
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
990
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
991
#endif
992
#endif
993
994
// [Apple] OS specific includes
995
#if defined(__APPLE__)
996
#include <TargetConditionals.h>
997
#endif
998
999
// Visual Studio warnings
1000
#ifdef _MSC_VER
1001
#pragma warning (disable: 4127)             // condition expression is constant
1002
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1003
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1004
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1005
#endif
1006
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1007
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1008
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1009
#endif
1010
1011
// Clang/GCC warnings with -Weverything
1012
#if defined(__clang__)
1013
#if __has_warning("-Wunknown-warning-option")
1014
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1015
#endif
1016
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1017
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1018
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1019
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1020
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1021
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1022
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1023
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1024
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1025
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1026
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1027
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1028
#elif defined(__GNUC__)
1029
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1030
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1031
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1032
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1033
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1034
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1035
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1036
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1037
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1038
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1039
#endif
1040
1041
// Debug options
1042
57.0k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1043
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1044
1045
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1046
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1047
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1048
1049
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1050
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1051
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1052
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1053
1054
// Tooltip offset
1055
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1056
1057
// Docking
1058
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1059
1060
//-------------------------------------------------------------------------
1061
// [SECTION] FORWARD DECLARATIONS
1062
//-------------------------------------------------------------------------
1063
1064
static void             SetCurrentWindow(ImGuiWindow* window);
1065
static void             FindHoveredWindow();
1066
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1067
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1068
1069
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1070
1071
// Settings
1072
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1073
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1074
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1075
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1076
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1077
1078
// Platform Dependents default implementation for IO functions
1079
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1080
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1081
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1082
1083
namespace ImGui
1084
{
1085
// Navigation
1086
static void             NavUpdate();
1087
static void             NavUpdateWindowing();
1088
static void             NavUpdateWindowingOverlay();
1089
static void             NavUpdateCancelRequest();
1090
static void             NavUpdateCreateMoveRequest();
1091
static void             NavUpdateCreateTabbingRequest();
1092
static float            NavUpdatePageUpPageDown();
1093
static inline void      NavUpdateAnyRequestFlag();
1094
static void             NavUpdateCreateWrappingRequest();
1095
static void             NavEndFrame();
1096
static bool             NavScoreItem(ImGuiNavItemData* result);
1097
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1098
static void             NavProcessItem();
1099
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1100
static ImVec2           NavCalcPreferredRefPos();
1101
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1102
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1103
static void             NavRestoreLayer(ImGuiNavLayer layer);
1104
static int              FindWindowFocusIndex(ImGuiWindow* window);
1105
1106
// Error Checking and Debug Tools
1107
static void             ErrorCheckNewFrameSanityChecks();
1108
static void             ErrorCheckEndFrameSanityChecks();
1109
static void             UpdateDebugToolItemPicker();
1110
static void             UpdateDebugToolStackQueries();
1111
1112
// Inputs
1113
static void             UpdateKeyboardInputs();
1114
static void             UpdateMouseInputs();
1115
static void             UpdateMouseWheel();
1116
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1117
1118
// Misc
1119
static void             UpdateSettings();
1120
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1121
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1122
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1123
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1124
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1125
static void             RenderDimmedBackgrounds();
1126
1127
// Viewports
1128
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1129
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1130
static void             DestroyViewport(ImGuiViewportP* viewport);
1131
static void             UpdateViewportsNewFrame();
1132
static void             UpdateViewportsEndFrame();
1133
static void             WindowSelectViewport(ImGuiWindow* window);
1134
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1135
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1136
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1137
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1138
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1139
static int              FindPlatformMonitorForRect(const ImRect& r);
1140
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1141
1142
}
1143
1144
//-----------------------------------------------------------------------------
1145
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1146
//-----------------------------------------------------------------------------
1147
1148
// DLL users:
1149
// - Heaps and globals are not shared across DLL boundaries!
1150
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1151
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1152
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1153
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1154
1155
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1156
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1157
//   Change to a different context by calling ImGui::SetCurrentContext().
1158
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1159
//   If you want thread-safety to allow N threads to access N different contexts:
1160
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1161
//         struct ImGuiContext;
1162
//         extern thread_local ImGuiContext* MyImGuiTLS;
1163
//         #define GImGui MyImGuiTLS
1164
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1165
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1166
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1167
// - DLL users: read comments above.
1168
#ifndef GImGui
1169
ImGuiContext*   GImGui = NULL;
1170
#endif
1171
1172
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1173
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1174
// - DLL users: read comments above.
1175
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1176
1.26k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1177
1.21k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1178
#else
1179
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1180
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1181
#endif
1182
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1183
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1184
static void*                GImAllocatorUserData = NULL;
1185
1186
//-----------------------------------------------------------------------------
1187
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1188
//-----------------------------------------------------------------------------
1189
1190
ImGuiStyle::ImGuiStyle()
1191
1
{
1192
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1193
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1194
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1195
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1196
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1197
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1198
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1199
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1200
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1201
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1202
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1203
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1204
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1205
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1206
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1207
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1208
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1209
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell. CellPadding.y may be altered between different rows.
1210
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1211
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1212
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1213
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1214
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1215
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1216
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1217
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1218
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1219
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1220
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1221
1
    TabBarBorderSize        = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1222
1
    TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1223
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1224
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1225
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1226
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1227
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1228
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1229
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1230
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1231
1
    DockingSeparatorSize    = 2.0f;             // Thickness of resizing border between docked windows
1232
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1233
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1234
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1235
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1236
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1237
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1238
1239
    // Behaviors
1240
1
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1241
1
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1242
1
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1243
1
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1244
1
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1245
1246
    // Default theme
1247
1
    ImGui::StyleColorsDark(this);
1248
1
}
1249
1250
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1251
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1252
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1253
0
{
1254
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1255
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1256
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1257
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1258
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1259
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1260
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1261
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1262
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1263
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1264
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1265
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1266
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1267
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1268
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1269
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1270
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1271
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1272
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1273
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1274
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1275
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1276
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1277
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1278
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1279
0
}
1280
1281
ImGuiIO::ImGuiIO()
1282
1
{
1283
    // Most fields are initialized with zero
1284
1
    memset(this, 0, sizeof(*this));
1285
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1286
1287
    // Settings
1288
1
    ConfigFlags = ImGuiConfigFlags_None;
1289
1
    BackendFlags = ImGuiBackendFlags_None;
1290
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1291
1
    DeltaTime = 1.0f / 60.0f;
1292
1
    IniSavingRate = 5.0f;
1293
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1294
1
    LogFilename = "imgui_log.txt";
1295
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1296
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1297
        KeyMap[i] = -1;
1298
#endif
1299
1
    UserData = NULL;
1300
1301
1
    Fonts = NULL;
1302
1
    FontGlobalScale = 1.0f;
1303
1
    FontDefault = NULL;
1304
1
    FontAllowUserScaling = false;
1305
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1306
1307
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1308
1
    ConfigDockingNoSplit = false;
1309
1
    ConfigDockingWithShift = false;
1310
1
    ConfigDockingAlwaysTabBar = false;
1311
1
    ConfigDockingTransparentPayload = false;
1312
1313
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1314
1
    ConfigViewportsNoAutoMerge = false;
1315
1
    ConfigViewportsNoTaskBarIcon = false;
1316
1
    ConfigViewportsNoDecoration = true;
1317
1
    ConfigViewportsNoDefaultParent = false;
1318
1319
    // Miscellaneous options
1320
1
    MouseDrawCursor = false;
1321
#ifdef __APPLE__
1322
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1323
#else
1324
1
    ConfigMacOSXBehaviors = false;
1325
1
#endif
1326
1
    ConfigInputTrickleEventQueue = true;
1327
1
    ConfigInputTextCursorBlink = true;
1328
1
    ConfigInputTextEnterKeepActive = false;
1329
1
    ConfigDragClickToInputText = false;
1330
1
    ConfigWindowsResizeFromEdges = true;
1331
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1332
1
    ConfigMemoryCompactTimer = 60.0f;
1333
1
    ConfigDebugBeginReturnValueOnce = false;
1334
1
    ConfigDebugBeginReturnValueLoop = false;
1335
1336
    // Inputs Behaviors
1337
1
    MouseDoubleClickTime = 0.30f;
1338
1
    MouseDoubleClickMaxDist = 6.0f;
1339
1
    MouseDragThreshold = 6.0f;
1340
1
    KeyRepeatDelay = 0.275f;
1341
1
    KeyRepeatRate = 0.050f;
1342
1343
    // Platform Functions
1344
    // Note: Initialize() will setup default clipboard/ime handlers.
1345
1
    BackendPlatformName = BackendRendererName = NULL;
1346
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1347
1
    PlatformLocaleDecimalPoint = '.';
1348
1349
    // Input (NB: we already have memset zero the entire structure!)
1350
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1351
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1352
1
    MouseSource = ImGuiMouseSource_Mouse;
1353
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1354
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1355
1
    AppAcceptingEvents = true;
1356
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1357
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1358
1
}
1359
1360
// Pass in translated ASCII characters for text input.
1361
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1362
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1363
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1364
void ImGuiIO::AddInputCharacter(unsigned int c)
1365
3.39k
{
1366
3.39k
    IM_ASSERT(Ctx != NULL);
1367
3.39k
    ImGuiContext& g = *Ctx;
1368
3.39k
    if (c == 0 || !AppAcceptingEvents)
1369
223
        return;
1370
1371
3.16k
    ImGuiInputEvent e;
1372
3.16k
    e.Type = ImGuiInputEventType_Text;
1373
3.16k
    e.Source = ImGuiInputSource_Keyboard;
1374
3.16k
    e.EventId = g.InputEventsNextEventId++;
1375
3.16k
    e.Text.Char = c;
1376
3.16k
    g.InputEventsQueue.push_back(e);
1377
3.16k
}
1378
1379
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1380
// we should save the high surrogate.
1381
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1382
3.24k
{
1383
3.24k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1384
186
        return;
1385
1386
3.05k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1387
448
    {
1388
448
        if (InputQueueSurrogate != 0)
1389
247
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1390
448
        InputQueueSurrogate = c;
1391
448
        return;
1392
448
    }
1393
1394
2.60k
    ImWchar cp = c;
1395
2.60k
    if (InputQueueSurrogate != 0)
1396
189
    {
1397
189
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1398
155
        {
1399
155
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1400
155
        }
1401
34
        else
1402
34
        {
1403
34
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1404
34
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1405
#else
1406
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1407
#endif
1408
34
        }
1409
1410
189
        InputQueueSurrogate = 0;
1411
189
    }
1412
2.60k
    AddInputCharacter((unsigned)cp);
1413
2.60k
}
1414
1415
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1416
38
{
1417
38
    if (!AppAcceptingEvents)
1418
0
        return;
1419
38
    while (*utf8_chars != 0)
1420
0
    {
1421
0
        unsigned int c = 0;
1422
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1423
0
        AddInputCharacter(c);
1424
0
    }
1425
38
}
1426
1427
// Clear all incoming events.
1428
void ImGuiIO::ClearEventsQueue()
1429
0
{
1430
0
    IM_ASSERT(Ctx != NULL);
1431
0
    ImGuiContext& g = *Ctx;
1432
0
    g.InputEventsQueue.clear();
1433
0
}
1434
1435
// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1436
void ImGuiIO::ClearInputKeys()
1437
5.36k
{
1438
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1439
    memset(KeysDown, 0, sizeof(KeysDown));
1440
#endif
1441
831k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1442
825k
    {
1443
825k
        KeysData[n].Down             = false;
1444
825k
        KeysData[n].DownDuration     = -1.0f;
1445
825k
        KeysData[n].DownDurationPrev = -1.0f;
1446
825k
    }
1447
5.36k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1448
5.36k
    KeyMods = ImGuiMod_None;
1449
5.36k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1450
32.1k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1451
26.8k
    {
1452
26.8k
        MouseDown[n] = false;
1453
26.8k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1454
26.8k
    }
1455
5.36k
    MouseWheel = MouseWheelH = 0.0f;
1456
5.36k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1457
5.36k
}
1458
1459
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1460
// Current frame character buffer is now also cleared by ClearInputKeys().
1461
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1462
void ImGuiIO::ClearInputCharacters()
1463
{
1464
    InputQueueCharacters.resize(0);
1465
}
1466
#endif
1467
1468
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1469
6.21k
{
1470
6.21k
    ImGuiContext& g = *ctx;
1471
9.23k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1472
5.06k
    {
1473
5.06k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1474
5.06k
        if (e->Type != type)
1475
1.90k
            continue;
1476
3.15k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1477
378
            continue;
1478
2.77k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1479
742
            continue;
1480
2.03k
        return e;
1481
2.77k
    }
1482
4.17k
    return NULL;
1483
6.21k
}
1484
1485
// Queue a new key down/up event.
1486
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1487
// - bool down:          Is the key down? use false to signify a key release.
1488
// - float analog_value: 0.0f..1.0f
1489
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1490
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1491
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1492
1.61k
{
1493
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1494
1.61k
    IM_ASSERT(Ctx != NULL);
1495
1.61k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1496
0
        return;
1497
1.61k
    ImGuiContext& g = *Ctx;
1498
1.61k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1499
1.61k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1500
1.61k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1501
1502
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1503
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1504
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1505
    if (BackendUsingLegacyKeyArrays == -1)
1506
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1507
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1508
    BackendUsingLegacyKeyArrays = 0;
1509
#endif
1510
1.61k
    if (ImGui::IsGamepadKey(key))
1511
15
        BackendUsingLegacyNavInputArray = false;
1512
1513
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1514
1.61k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1515
1.61k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1516
1.61k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1517
1.61k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1518
1.61k
    if (latest_key_down == down && latest_key_analog == analog_value)
1519
308
        return;
1520
1521
    // Add event
1522
1.30k
    ImGuiInputEvent e;
1523
1.30k
    e.Type = ImGuiInputEventType_Key;
1524
1.30k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1525
1.30k
    e.EventId = g.InputEventsNextEventId++;
1526
1.30k
    e.Key.Key = key;
1527
1.30k
    e.Key.Down = down;
1528
1.30k
    e.Key.AnalogValue = analog_value;
1529
1.30k
    g.InputEventsQueue.push_back(e);
1530
1.30k
}
1531
1532
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1533
1.30k
{
1534
1.30k
    if (!AppAcceptingEvents)
1535
0
        return;
1536
1.30k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1537
1.30k
}
1538
1539
// [Optional] Call after AddKeyEvent().
1540
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1541
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1542
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1543
0
{
1544
0
    if (key == ImGuiKey_None)
1545
0
        return;
1546
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1547
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1548
0
    IM_UNUSED(native_keycode);  // Yet unused
1549
0
    IM_UNUSED(native_scancode); // Yet unused
1550
1551
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1552
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1553
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1554
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1555
        return;
1556
    KeyMap[legacy_key] = key;
1557
    KeyMap[key] = legacy_key;
1558
#else
1559
0
    IM_UNUSED(key);
1560
0
    IM_UNUSED(native_legacy_index);
1561
0
#endif
1562
0
}
1563
1564
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1565
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1566
0
{
1567
0
    AppAcceptingEvents = accepting_events;
1568
0
}
1569
1570
// Queue a mouse move event
1571
void ImGuiIO::AddMousePosEvent(float x, float y)
1572
1.97k
{
1573
1.97k
    IM_ASSERT(Ctx != NULL);
1574
1.97k
    ImGuiContext& g = *Ctx;
1575
1.97k
    if (!AppAcceptingEvents)
1576
0
        return;
1577
1578
    // Apply same flooring as UpdateMouseInputs()
1579
1.97k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1580
1581
    // Filter duplicate
1582
1.97k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1583
1.97k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1584
1.97k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1585
657
        return;
1586
1587
1.31k
    ImGuiInputEvent e;
1588
1.31k
    e.Type = ImGuiInputEventType_MousePos;
1589
1.31k
    e.Source = ImGuiInputSource_Mouse;
1590
1.31k
    e.EventId = g.InputEventsNextEventId++;
1591
1.31k
    e.MousePos.PosX = pos.x;
1592
1.31k
    e.MousePos.PosY = pos.y;
1593
1.31k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1594
1.31k
    g.InputEventsQueue.push_back(e);
1595
1.31k
}
1596
1597
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1598
2.17k
{
1599
2.17k
    IM_ASSERT(Ctx != NULL);
1600
2.17k
    ImGuiContext& g = *Ctx;
1601
2.17k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1602
2.17k
    if (!AppAcceptingEvents)
1603
0
        return;
1604
1605
    // Filter duplicate
1606
2.17k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1607
2.17k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1608
2.17k
    if (latest_button_down == down)
1609
965
        return;
1610
1611
1.20k
    ImGuiInputEvent e;
1612
1.20k
    e.Type = ImGuiInputEventType_MouseButton;
1613
1.20k
    e.Source = ImGuiInputSource_Mouse;
1614
1.20k
    e.EventId = g.InputEventsNextEventId++;
1615
1.20k
    e.MouseButton.Button = mouse_button;
1616
1.20k
    e.MouseButton.Down = down;
1617
1.20k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1618
1.20k
    g.InputEventsQueue.push_back(e);
1619
1.20k
}
1620
1621
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1622
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1623
762
{
1624
762
    IM_ASSERT(Ctx != NULL);
1625
762
    ImGuiContext& g = *Ctx;
1626
1627
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1628
762
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1629
21
        return;
1630
1631
741
    ImGuiInputEvent e;
1632
741
    e.Type = ImGuiInputEventType_MouseWheel;
1633
741
    e.Source = ImGuiInputSource_Mouse;
1634
741
    e.EventId = g.InputEventsNextEventId++;
1635
741
    e.MouseWheel.WheelX = wheel_x;
1636
741
    e.MouseWheel.WheelY = wheel_y;
1637
741
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1638
741
    g.InputEventsQueue.push_back(e);
1639
741
}
1640
1641
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1642
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1643
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1644
0
{
1645
0
    IM_ASSERT(Ctx != NULL);
1646
0
    ImGuiContext& g = *Ctx;
1647
0
    g.InputEventsNextMouseSource = source;
1648
0
}
1649
1650
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1651
0
{
1652
0
    IM_ASSERT(Ctx != NULL);
1653
0
    ImGuiContext& g = *Ctx;
1654
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1655
0
    if (!AppAcceptingEvents)
1656
0
        return;
1657
1658
    // Filter duplicate
1659
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1660
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1661
0
    if (latest_viewport_id == viewport_id)
1662
0
        return;
1663
1664
0
    ImGuiInputEvent e;
1665
0
    e.Type = ImGuiInputEventType_MouseViewport;
1666
0
    e.Source = ImGuiInputSource_Mouse;
1667
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1668
0
    g.InputEventsQueue.push_back(e);
1669
0
}
1670
1671
void ImGuiIO::AddFocusEvent(bool focused)
1672
459
{
1673
459
    IM_ASSERT(Ctx != NULL);
1674
459
    ImGuiContext& g = *Ctx;
1675
1676
    // Filter duplicate
1677
459
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1678
459
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1679
459
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1680
188
        return;
1681
1682
271
    ImGuiInputEvent e;
1683
271
    e.Type = ImGuiInputEventType_Focus;
1684
271
    e.EventId = g.InputEventsNextEventId++;
1685
271
    e.AppFocused.Focused = focused;
1686
271
    g.InputEventsQueue.push_back(e);
1687
271
}
1688
1689
//-----------------------------------------------------------------------------
1690
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1691
//-----------------------------------------------------------------------------
1692
1693
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1694
0
{
1695
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1696
0
    ImVec2 p_last = p1;
1697
0
    ImVec2 p_closest;
1698
0
    float p_closest_dist2 = FLT_MAX;
1699
0
    float t_step = 1.0f / (float)num_segments;
1700
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1701
0
    {
1702
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1703
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1704
0
        float dist2 = ImLengthSqr(p - p_line);
1705
0
        if (dist2 < p_closest_dist2)
1706
0
        {
1707
0
            p_closest = p_line;
1708
0
            p_closest_dist2 = dist2;
1709
0
        }
1710
0
        p_last = p_current;
1711
0
    }
1712
0
    return p_closest;
1713
0
}
1714
1715
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1716
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1717
0
{
1718
0
    float dx = x4 - x1;
1719
0
    float dy = y4 - y1;
1720
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1721
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1722
0
    d2 = (d2 >= 0) ? d2 : -d2;
1723
0
    d3 = (d3 >= 0) ? d3 : -d3;
1724
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1725
0
    {
1726
0
        ImVec2 p_current(x4, y4);
1727
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1728
0
        float dist2 = ImLengthSqr(p - p_line);
1729
0
        if (dist2 < p_closest_dist2)
1730
0
        {
1731
0
            p_closest = p_line;
1732
0
            p_closest_dist2 = dist2;
1733
0
        }
1734
0
        p_last = p_current;
1735
0
    }
1736
0
    else if (level < 10)
1737
0
    {
1738
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1739
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1740
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1741
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1742
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1743
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1744
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1745
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1746
0
    }
1747
0
}
1748
1749
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1750
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1751
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1752
0
{
1753
0
    IM_ASSERT(tess_tol > 0.0f);
1754
0
    ImVec2 p_last = p1;
1755
0
    ImVec2 p_closest;
1756
0
    float p_closest_dist2 = FLT_MAX;
1757
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1758
0
    return p_closest;
1759
0
}
1760
1761
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1762
0
{
1763
0
    ImVec2 ap = p - a;
1764
0
    ImVec2 ab_dir = b - a;
1765
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1766
0
    if (dot < 0.0f)
1767
0
        return a;
1768
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1769
0
    if (dot > ab_len_sqr)
1770
0
        return b;
1771
0
    return a + ab_dir * dot / ab_len_sqr;
1772
0
}
1773
1774
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1775
0
{
1776
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1777
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1778
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1779
0
    return ((b1 == b2) && (b2 == b3));
1780
0
}
1781
1782
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1783
0
{
1784
0
    ImVec2 v0 = b - a;
1785
0
    ImVec2 v1 = c - a;
1786
0
    ImVec2 v2 = p - a;
1787
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1788
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1789
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1790
0
    out_u = 1.0f - out_v - out_w;
1791
0
}
1792
1793
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1794
0
{
1795
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1796
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1797
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1798
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1799
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1800
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1801
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1802
0
    if (m == dist2_ab)
1803
0
        return proj_ab;
1804
0
    if (m == dist2_bc)
1805
0
        return proj_bc;
1806
0
    return proj_ca;
1807
0
}
1808
1809
//-----------------------------------------------------------------------------
1810
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1811
//-----------------------------------------------------------------------------
1812
1813
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1814
int ImStricmp(const char* str1, const char* str2)
1815
0
{
1816
0
    int d;
1817
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1818
0
    return d;
1819
0
}
1820
1821
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1822
0
{
1823
0
    int d = 0;
1824
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1825
0
    return d;
1826
0
}
1827
1828
void ImStrncpy(char* dst, const char* src, size_t count)
1829
16
{
1830
16
    if (count < 1)
1831
0
        return;
1832
16
    if (count > 1)
1833
16
        strncpy(dst, src, count - 1);
1834
16
    dst[count - 1] = 0;
1835
16
}
1836
1837
char* ImStrdup(const char* str)
1838
4
{
1839
4
    size_t len = strlen(str);
1840
4
    void* buf = IM_ALLOC(len + 1);
1841
4
    return (char*)memcpy(buf, (const void*)str, len + 1);
1842
4
}
1843
1844
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1845
0
{
1846
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1847
0
    size_t src_size = strlen(src) + 1;
1848
0
    if (dst_buf_size < src_size)
1849
0
    {
1850
0
        IM_FREE(dst);
1851
0
        dst = (char*)IM_ALLOC(src_size);
1852
0
        if (p_dst_size)
1853
0
            *p_dst_size = src_size;
1854
0
    }
1855
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1856
0
}
1857
1858
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1859
0
{
1860
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1861
0
    return p;
1862
0
}
1863
1864
int ImStrlenW(const ImWchar* str)
1865
0
{
1866
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1867
0
    int n = 0;
1868
0
    while (*str++) n++;
1869
0
    return n;
1870
0
}
1871
1872
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1873
const char* ImStreolRange(const char* str, const char* str_end)
1874
0
{
1875
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1876
0
    return p ? p : str_end;
1877
0
}
1878
1879
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1880
0
{
1881
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1882
0
        buf_mid_line--;
1883
0
    return buf_mid_line;
1884
0
}
1885
1886
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1887
0
{
1888
0
    if (!needle_end)
1889
0
        needle_end = needle + strlen(needle);
1890
1891
0
    const char un0 = (char)ImToUpper(*needle);
1892
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1893
0
    {
1894
0
        if (ImToUpper(*haystack) == un0)
1895
0
        {
1896
0
            const char* b = needle + 1;
1897
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1898
0
                if (ImToUpper(*a) != ImToUpper(*b))
1899
0
                    break;
1900
0
            if (b == needle_end)
1901
0
                return haystack;
1902
0
        }
1903
0
        haystack++;
1904
0
    }
1905
0
    return NULL;
1906
0
}
1907
1908
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1909
void ImStrTrimBlanks(char* buf)
1910
0
{
1911
0
    char* p = buf;
1912
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1913
0
        p++;
1914
0
    char* p_start = p;
1915
0
    while (*p != 0)                         // Find end of string
1916
0
        p++;
1917
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1918
0
        p--;
1919
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1920
0
        memmove(buf, p_start, p - p_start);
1921
0
    buf[p - p_start] = 0;                   // Zero terminate
1922
0
}
1923
1924
const char* ImStrSkipBlank(const char* str)
1925
0
{
1926
0
    while (str[0] == ' ' || str[0] == '\t')
1927
0
        str++;
1928
0
    return str;
1929
0
}
1930
1931
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1932
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1933
// B) When buf==NULL vsnprintf() will return the output size.
1934
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1935
1936
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1937
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1938
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1939
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1940
#ifdef IMGUI_USE_STB_SPRINTF
1941
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1942
#define STB_SPRINTF_IMPLEMENTATION
1943
#endif
1944
#ifdef IMGUI_STB_SPRINTF_FILENAME
1945
#include IMGUI_STB_SPRINTF_FILENAME
1946
#else
1947
#include "stb_sprintf.h"
1948
#endif
1949
#endif // #ifdef IMGUI_USE_STB_SPRINTF
1950
1951
#if defined(_MSC_VER) && !defined(vsnprintf)
1952
#define vsnprintf _vsnprintf
1953
#endif
1954
1955
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1956
30
{
1957
30
    va_list args;
1958
30
    va_start(args, fmt);
1959
#ifdef IMGUI_USE_STB_SPRINTF
1960
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1961
#else
1962
30
    int w = vsnprintf(buf, buf_size, fmt, args);
1963
30
#endif
1964
30
    va_end(args);
1965
30
    if (buf == NULL)
1966
0
        return w;
1967
30
    if (w == -1 || w >= (int)buf_size)
1968
0
        w = (int)buf_size - 1;
1969
30
    buf[w] = 0;
1970
30
    return w;
1971
30
}
1972
1973
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1974
23.6k
{
1975
#ifdef IMGUI_USE_STB_SPRINTF
1976
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1977
#else
1978
23.6k
    int w = vsnprintf(buf, buf_size, fmt, args);
1979
23.6k
#endif
1980
23.6k
    if (buf == NULL)
1981
0
        return w;
1982
23.6k
    if (w == -1 || w >= (int)buf_size)
1983
0
        w = (int)buf_size - 1;
1984
23.6k
    buf[w] = 0;
1985
23.6k
    return w;
1986
23.6k
}
1987
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1988
1989
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1990
23.6k
{
1991
23.6k
    va_list args;
1992
23.6k
    va_start(args, fmt);
1993
23.6k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
1994
23.6k
    va_end(args);
1995
23.6k
}
1996
1997
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1998
23.6k
{
1999
23.6k
    ImGuiContext& g = *GImGui;
2000
23.6k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2001
29
    {
2002
29
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2003
29
        *out_buf = buf;
2004
29
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2005
29
    }
2006
23.6k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2007
0
    {
2008
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2009
0
        const char* buf = va_arg(args, const char*);
2010
0
        *out_buf = buf;
2011
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2012
0
    }
2013
23.6k
    else
2014
23.6k
    {
2015
23.6k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2016
23.6k
        *out_buf = g.TempBuffer.Data;
2017
23.6k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2018
23.6k
    }
2019
23.6k
}
2020
2021
// CRC32 needs a 1KB lookup table (not cache friendly)
2022
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2023
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2024
static const ImU32 GCrc32LookupTable[256] =
2025
{
2026
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2027
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2028
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2029
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2030
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2031
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2032
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2033
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2034
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2035
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2036
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2037
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2038
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2039
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2040
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2041
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2042
};
2043
2044
// Known size hash
2045
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2046
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2047
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2048
23.6k
{
2049
23.6k
    ImU32 crc = ~seed;
2050
23.6k
    const unsigned char* data = (const unsigned char*)data_p;
2051
23.6k
    const ImU32* crc32_lut = GCrc32LookupTable;
2052
118k
    while (data_size-- != 0)
2053
94.4k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2054
23.6k
    return ~crc;
2055
23.6k
}
2056
2057
// Zero-terminated string hash, with support for ### to reset back to seed value
2058
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2059
// Because this syntax is rarely used we are optimizing for the common case.
2060
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2061
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2062
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2063
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2064
240k
{
2065
240k
    seed = ~seed;
2066
240k
    ImU32 crc = seed;
2067
240k
    const unsigned char* data = (const unsigned char*)data_p;
2068
240k
    const ImU32* crc32_lut = GCrc32LookupTable;
2069
240k
    if (data_size != 0)
2070
0
    {
2071
0
        while (data_size-- != 0)
2072
0
        {
2073
0
            unsigned char c = *data++;
2074
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2075
0
                crc = seed;
2076
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2077
0
        }
2078
0
    }
2079
240k
    else
2080
240k
    {
2081
3.12M
        while (unsigned char c = *data++)
2082
2.88M
        {
2083
2.88M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2084
24.1k
                crc = seed;
2085
2.88M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2086
2.88M
        }
2087
240k
    }
2088
240k
    return ~crc;
2089
240k
}
2090
2091
//-----------------------------------------------------------------------------
2092
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2093
//-----------------------------------------------------------------------------
2094
2095
// Default file functions
2096
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2097
2098
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2099
0
{
2100
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2101
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2102
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2103
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2104
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2105
    ImGuiContext& g = *GImGui;
2106
    g.TempBuffer.reserve((filename_wsize + mode_wsize) * sizeof(wchar_t));
2107
    wchar_t* buf = (wchar_t*)(void*)g.TempBuffer.Data;
2108
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2109
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2110
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2111
#else
2112
0
    return fopen(filename, mode);
2113
0
#endif
2114
0
}
2115
2116
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2117
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2118
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2119
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2120
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2121
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2122
2123
// Helper: Load file content into memory
2124
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2125
// This can't really be used with "rt" because fseek size won't match read size.
2126
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2127
0
{
2128
0
    IM_ASSERT(filename && mode);
2129
0
    if (out_file_size)
2130
0
        *out_file_size = 0;
2131
2132
0
    ImFileHandle f;
2133
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2134
0
        return NULL;
2135
2136
0
    size_t file_size = (size_t)ImFileGetSize(f);
2137
0
    if (file_size == (size_t)-1)
2138
0
    {
2139
0
        ImFileClose(f);
2140
0
        return NULL;
2141
0
    }
2142
2143
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2144
0
    if (file_data == NULL)
2145
0
    {
2146
0
        ImFileClose(f);
2147
0
        return NULL;
2148
0
    }
2149
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2150
0
    {
2151
0
        ImFileClose(f);
2152
0
        IM_FREE(file_data);
2153
0
        return NULL;
2154
0
    }
2155
0
    if (padding_bytes > 0)
2156
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2157
2158
0
    ImFileClose(f);
2159
0
    if (out_file_size)
2160
0
        *out_file_size = file_size;
2161
2162
0
    return file_data;
2163
0
}
2164
2165
//-----------------------------------------------------------------------------
2166
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2167
//-----------------------------------------------------------------------------
2168
2169
IM_MSVC_RUNTIME_CHECKS_OFF
2170
2171
// Convert UTF-8 to 32-bit character, process single character input.
2172
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2173
// We handle UTF-8 decoding error by skipping forward.
2174
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2175
3.84M
{
2176
3.84M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2177
3.84M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2178
3.84M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2179
3.84M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2180
3.84M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2181
3.84M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2182
3.84M
    int wanted = len + (len ? 0 : 1);
2183
2184
3.84M
    if (in_text_end == NULL)
2185
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2186
2187
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2188
    // so it is fast even with excessive branching.
2189
3.84M
    unsigned char s[4];
2190
3.84M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2191
3.84M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2192
3.84M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2193
3.84M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2194
2195
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2196
3.84M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2197
3.84M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2198
3.84M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2199
3.84M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2200
3.84M
    *out_char >>= shiftc[len];
2201
2202
    // Accumulate the various error conditions.
2203
3.84M
    int e = 0;
2204
3.84M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2205
3.84M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2206
3.84M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2207
3.84M
    e |= (s[1] & 0xc0) >> 2;
2208
3.84M
    e |= (s[2] & 0xc0) >> 4;
2209
3.84M
    e |= (s[3]       ) >> 6;
2210
3.84M
    e ^= 0x2a; // top two bits of each tail byte correct?
2211
3.84M
    e >>= shifte[len];
2212
2213
3.84M
    if (e)
2214
3.81k
    {
2215
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2216
        // One byte is consumed in case of invalid first byte of in_text.
2217
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2218
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2219
3.81k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2220
3.81k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2221
3.81k
    }
2222
2223
3.84M
    return wanted;
2224
3.84M
}
2225
2226
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2227
0
{
2228
0
    ImWchar* buf_out = buf;
2229
0
    ImWchar* buf_end = buf + buf_size;
2230
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2231
0
    {
2232
0
        unsigned int c;
2233
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2234
0
        *buf_out++ = (ImWchar)c;
2235
0
    }
2236
0
    *buf_out = 0;
2237
0
    if (in_text_remaining)
2238
0
        *in_text_remaining = in_text;
2239
0
    return (int)(buf_out - buf);
2240
0
}
2241
2242
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2243
0
{
2244
0
    int char_count = 0;
2245
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2246
0
    {
2247
0
        unsigned int c;
2248
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2249
0
        char_count++;
2250
0
    }
2251
0
    return char_count;
2252
0
}
2253
2254
// Based on stb_to_utf8() from github.com/nothings/stb/
2255
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2256
0
{
2257
0
    if (c < 0x80)
2258
0
    {
2259
0
        buf[0] = (char)c;
2260
0
        return 1;
2261
0
    }
2262
0
    if (c < 0x800)
2263
0
    {
2264
0
        if (buf_size < 2) return 0;
2265
0
        buf[0] = (char)(0xc0 + (c >> 6));
2266
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2267
0
        return 2;
2268
0
    }
2269
0
    if (c < 0x10000)
2270
0
    {
2271
0
        if (buf_size < 3) return 0;
2272
0
        buf[0] = (char)(0xe0 + (c >> 12));
2273
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2274
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2275
0
        return 3;
2276
0
    }
2277
0
    if (c <= 0x10FFFF)
2278
0
    {
2279
0
        if (buf_size < 4) return 0;
2280
0
        buf[0] = (char)(0xf0 + (c >> 18));
2281
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2282
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2283
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2284
0
        return 4;
2285
0
    }
2286
    // Invalid code point, the max unicode is 0x10FFFF
2287
0
    return 0;
2288
0
}
2289
2290
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2291
0
{
2292
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2293
0
    out_buf[count] = 0;
2294
0
    return out_buf;
2295
0
}
2296
2297
// Not optimal but we very rarely use this function.
2298
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2299
0
{
2300
0
    unsigned int unused = 0;
2301
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2302
0
}
2303
2304
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2305
0
{
2306
0
    if (c < 0x80) return 1;
2307
0
    if (c < 0x800) return 2;
2308
0
    if (c < 0x10000) return 3;
2309
0
    if (c <= 0x10FFFF) return 4;
2310
0
    return 3;
2311
0
}
2312
2313
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2314
0
{
2315
0
    char* buf_p = out_buf;
2316
0
    const char* buf_end = out_buf + out_buf_size;
2317
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2318
0
    {
2319
0
        unsigned int c = (unsigned int)(*in_text++);
2320
0
        if (c < 0x80)
2321
0
            *buf_p++ = (char)c;
2322
0
        else
2323
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2324
0
    }
2325
0
    *buf_p = 0;
2326
0
    return (int)(buf_p - out_buf);
2327
0
}
2328
2329
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2330
0
{
2331
0
    int bytes_count = 0;
2332
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2333
0
    {
2334
0
        unsigned int c = (unsigned int)(*in_text++);
2335
0
        if (c < 0x80)
2336
0
            bytes_count++;
2337
0
        else
2338
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2339
0
    }
2340
0
    return bytes_count;
2341
0
}
2342
2343
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2344
0
{
2345
0
    while (in_text_curr > in_text_start)
2346
0
    {
2347
0
        in_text_curr--;
2348
0
        if ((*in_text_curr & 0xC0) != 0x80)
2349
0
            return in_text_curr;
2350
0
    }
2351
0
    return in_text_start;
2352
0
}
2353
2354
IM_MSVC_RUNTIME_CHECKS_RESTORE
2355
2356
//-----------------------------------------------------------------------------
2357
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2358
// Note: The Convert functions are early design which are not consistent with other API.
2359
//-----------------------------------------------------------------------------
2360
2361
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2362
0
{
2363
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2364
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2365
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2366
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2367
0
    return IM_COL32(r, g, b, 0xFF);
2368
0
}
2369
2370
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2371
97.1k
{
2372
97.1k
    float s = 1.0f / 255.0f;
2373
97.1k
    return ImVec4(
2374
97.1k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2375
97.1k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2376
97.1k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2377
97.1k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2378
97.1k
}
2379
2380
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2381
459k
{
2382
459k
    ImU32 out;
2383
459k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2384
459k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2385
459k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2386
459k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2387
459k
    return out;
2388
459k
}
2389
2390
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2391
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2392
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2393
0
{
2394
0
    float K = 0.f;
2395
0
    if (g < b)
2396
0
    {
2397
0
        ImSwap(g, b);
2398
0
        K = -1.f;
2399
0
    }
2400
0
    if (r < g)
2401
0
    {
2402
0
        ImSwap(r, g);
2403
0
        K = -2.f / 6.f - K;
2404
0
    }
2405
2406
0
    const float chroma = r - (g < b ? g : b);
2407
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2408
0
    out_s = chroma / (r + 1e-20f);
2409
0
    out_v = r;
2410
0
}
2411
2412
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2413
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2414
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2415
0
{
2416
0
    if (s == 0.0f)
2417
0
    {
2418
        // gray
2419
0
        out_r = out_g = out_b = v;
2420
0
        return;
2421
0
    }
2422
2423
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2424
0
    int   i = (int)h;
2425
0
    float f = h - (float)i;
2426
0
    float p = v * (1.0f - s);
2427
0
    float q = v * (1.0f - s * f);
2428
0
    float t = v * (1.0f - s * (1.0f - f));
2429
2430
0
    switch (i)
2431
0
    {
2432
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2433
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2434
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2435
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2436
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2437
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2438
0
    }
2439
0
}
2440
2441
//-----------------------------------------------------------------------------
2442
// [SECTION] ImGuiStorage
2443
// Helper: Key->value storage
2444
//-----------------------------------------------------------------------------
2445
2446
// std::lower_bound but without the bullshit
2447
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2448
71.8k
{
2449
71.8k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2450
71.8k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2451
71.8k
    size_t count = (size_t)(last - first);
2452
239k
    while (count > 0)
2453
167k
    {
2454
167k
        size_t count2 = count >> 1;
2455
167k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2456
167k
        if (mid->key < key)
2457
47.7k
        {
2458
47.7k
            first = ++mid;
2459
47.7k
            count -= count2 + 1;
2460
47.7k
        }
2461
119k
        else
2462
119k
        {
2463
119k
            count = count2;
2464
119k
        }
2465
167k
    }
2466
71.8k
    return first;
2467
71.8k
}
2468
2469
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2470
void ImGuiStorage::BuildSortByKey()
2471
0
{
2472
0
    struct StaticFunc
2473
0
    {
2474
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2475
0
        {
2476
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2477
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2478
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2479
0
            return 0;
2480
0
        }
2481
0
    };
2482
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2483
0
}
2484
2485
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2486
0
{
2487
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2488
0
    if (it == Data.end() || it->key != key)
2489
0
        return default_val;
2490
0
    return it->val_i;
2491
0
}
2492
2493
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2494
0
{
2495
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2496
0
}
2497
2498
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2499
0
{
2500
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2501
0
    if (it == Data.end() || it->key != key)
2502
0
        return default_val;
2503
0
    return it->val_f;
2504
0
}
2505
2506
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2507
71.8k
{
2508
71.8k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2509
71.8k
    if (it == Data.end() || it->key != key)
2510
4
        return NULL;
2511
71.8k
    return it->val_p;
2512
71.8k
}
2513
2514
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2515
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2516
0
{
2517
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2518
0
    if (it == Data.end() || it->key != key)
2519
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2520
0
    return &it->val_i;
2521
0
}
2522
2523
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2524
0
{
2525
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2526
0
}
2527
2528
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2529
0
{
2530
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2531
0
    if (it == Data.end() || it->key != key)
2532
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2533
0
    return &it->val_f;
2534
0
}
2535
2536
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2537
0
{
2538
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2539
0
    if (it == Data.end() || it->key != key)
2540
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2541
0
    return &it->val_p;
2542
0
}
2543
2544
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2545
void ImGuiStorage::SetInt(ImGuiID key, int val)
2546
0
{
2547
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2548
0
    if (it == Data.end() || it->key != key)
2549
0
        Data.insert(it, ImGuiStoragePair(key, val));
2550
0
    else
2551
0
        it->val_i = val;
2552
0
}
2553
2554
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2555
0
{
2556
0
    SetInt(key, val ? 1 : 0);
2557
0
}
2558
2559
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2560
0
{
2561
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2562
0
    if (it == Data.end() || it->key != key)
2563
0
        Data.insert(it, ImGuiStoragePair(key, val));
2564
0
    else
2565
0
        it->val_f = val;
2566
0
}
2567
2568
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2569
4
{
2570
4
    ImGuiStoragePair* it = LowerBound(Data, key);
2571
4
    if (it == Data.end() || it->key != key)
2572
4
        Data.insert(it, ImGuiStoragePair(key, val));
2573
0
    else
2574
0
        it->val_p = val;
2575
4
}
2576
2577
void ImGuiStorage::SetAllInt(int v)
2578
0
{
2579
0
    for (int i = 0; i < Data.Size; i++)
2580
0
        Data[i].val_i = v;
2581
0
}
2582
2583
//-----------------------------------------------------------------------------
2584
// [SECTION] ImGuiTextFilter
2585
//-----------------------------------------------------------------------------
2586
2587
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2588
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2589
0
{
2590
0
    InputBuf[0] = 0;
2591
0
    CountGrep = 0;
2592
0
    if (default_filter)
2593
0
    {
2594
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2595
0
        Build();
2596
0
    }
2597
0
}
2598
2599
bool ImGuiTextFilter::Draw(const char* label, float width)
2600
0
{
2601
0
    if (width != 0.0f)
2602
0
        ImGui::SetNextItemWidth(width);
2603
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2604
0
    if (value_changed)
2605
0
        Build();
2606
0
    return value_changed;
2607
0
}
2608
2609
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2610
0
{
2611
0
    out->resize(0);
2612
0
    const char* wb = b;
2613
0
    const char* we = wb;
2614
0
    while (we < e)
2615
0
    {
2616
0
        if (*we == separator)
2617
0
        {
2618
0
            out->push_back(ImGuiTextRange(wb, we));
2619
0
            wb = we + 1;
2620
0
        }
2621
0
        we++;
2622
0
    }
2623
0
    if (wb != we)
2624
0
        out->push_back(ImGuiTextRange(wb, we));
2625
0
}
2626
2627
void ImGuiTextFilter::Build()
2628
0
{
2629
0
    Filters.resize(0);
2630
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2631
0
    input_range.split(',', &Filters);
2632
2633
0
    CountGrep = 0;
2634
0
    for (ImGuiTextRange& f : Filters)
2635
0
    {
2636
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2637
0
            f.b++;
2638
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2639
0
            f.e--;
2640
0
        if (f.empty())
2641
0
            continue;
2642
0
        if (f.b[0] != '-')
2643
0
            CountGrep += 1;
2644
0
    }
2645
0
}
2646
2647
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2648
0
{
2649
0
    if (Filters.empty())
2650
0
        return true;
2651
2652
0
    if (text == NULL)
2653
0
        text = "";
2654
2655
0
    for (const ImGuiTextRange& f : Filters)
2656
0
    {
2657
0
        if (f.empty())
2658
0
            continue;
2659
0
        if (f.b[0] == '-')
2660
0
        {
2661
            // Subtract
2662
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2663
0
                return false;
2664
0
        }
2665
0
        else
2666
0
        {
2667
            // Grep
2668
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2669
0
                return true;
2670
0
        }
2671
0
    }
2672
2673
    // Implicit * grep
2674
0
    if (CountGrep == 0)
2675
0
        return true;
2676
2677
0
    return false;
2678
0
}
2679
2680
//-----------------------------------------------------------------------------
2681
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2682
//-----------------------------------------------------------------------------
2683
2684
// On some platform vsnprintf() takes va_list by reference and modifies it.
2685
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2686
#ifndef va_copy
2687
#if defined(__GNUC__) || defined(__clang__)
2688
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2689
#else
2690
#define va_copy(dest, src) (dest = src)
2691
#endif
2692
#endif
2693
2694
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2695
2696
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2697
0
{
2698
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2699
2700
    // Add zero-terminator the first time
2701
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2702
0
    const int needed_sz = write_off + len;
2703
0
    if (write_off + len >= Buf.Capacity)
2704
0
    {
2705
0
        int new_capacity = Buf.Capacity * 2;
2706
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2707
0
    }
2708
2709
0
    Buf.resize(needed_sz);
2710
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2711
0
    Buf[write_off - 1 + len] = 0;
2712
0
}
2713
2714
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2715
0
{
2716
0
    va_list args;
2717
0
    va_start(args, fmt);
2718
0
    appendfv(fmt, args);
2719
0
    va_end(args);
2720
0
}
2721
2722
// Helper: Text buffer for logging/accumulating text
2723
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2724
0
{
2725
0
    va_list args_copy;
2726
0
    va_copy(args_copy, args);
2727
2728
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2729
0
    if (len <= 0)
2730
0
    {
2731
0
        va_end(args_copy);
2732
0
        return;
2733
0
    }
2734
2735
    // Add zero-terminator the first time
2736
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2737
0
    const int needed_sz = write_off + len;
2738
0
    if (write_off + len >= Buf.Capacity)
2739
0
    {
2740
0
        int new_capacity = Buf.Capacity * 2;
2741
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2742
0
    }
2743
2744
0
    Buf.resize(needed_sz);
2745
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2746
0
    va_end(args_copy);
2747
0
}
2748
2749
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2750
0
{
2751
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2752
0
    if (old_size == new_size)
2753
0
        return;
2754
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2755
0
        LineOffsets.push_back(EndOffset);
2756
0
    const char* base_end = base + new_size;
2757
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2758
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2759
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2760
0
    EndOffset = ImMax(EndOffset, new_size);
2761
0
}
2762
2763
//-----------------------------------------------------------------------------
2764
// [SECTION] ImGuiListClipper
2765
//-----------------------------------------------------------------------------
2766
2767
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2768
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2769
static bool GetSkipItemForListClipping()
2770
0
{
2771
0
    ImGuiContext& g = *GImGui;
2772
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2773
0
}
2774
2775
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2776
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2777
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2778
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2779
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2780
{
2781
    ImGuiContext& g = *GImGui;
2782
    ImGuiWindow* window = g.CurrentWindow;
2783
    if (g.LogEnabled)
2784
    {
2785
        // If logging is active, do not perform any clipping
2786
        *out_items_display_start = 0;
2787
        *out_items_display_end = items_count;
2788
        return;
2789
    }
2790
    if (GetSkipItemForListClipping())
2791
    {
2792
        *out_items_display_start = *out_items_display_end = 0;
2793
        return;
2794
    }
2795
2796
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2797
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2798
    ImRect rect = window->ClipRect;
2799
    if (g.NavMoveScoringItems)
2800
        rect.Add(g.NavScoringNoClipRect);
2801
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2802
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2803
2804
    const ImVec2 pos = window->DC.CursorPos;
2805
    int start = (int)((rect.Min.y - pos.y) / items_height);
2806
    int end = (int)((rect.Max.y - pos.y) / items_height);
2807
2808
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2809
    // FIXME: Verify this works with tabbing
2810
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2811
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2812
        start--;
2813
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2814
        end++;
2815
2816
    start = ImClamp(start, 0, items_count);
2817
    end = ImClamp(end + 1, start, items_count);
2818
    *out_items_display_start = start;
2819
    *out_items_display_end = end;
2820
}
2821
#endif
2822
2823
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2824
0
{
2825
0
    if (ranges.Size - offset <= 1)
2826
0
        return;
2827
2828
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2829
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2830
0
        for (int i = offset; i < sort_end + offset; ++i)
2831
0
            if (ranges[i].Min > ranges[i + 1].Min)
2832
0
                ImSwap(ranges[i], ranges[i + 1]);
2833
2834
    // Now fuse ranges together as much as possible.
2835
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2836
0
    {
2837
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2838
0
        if (ranges[i - 1].Max < ranges[i].Min)
2839
0
            continue;
2840
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2841
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2842
0
        ranges.erase(ranges.Data + i);
2843
0
        i--;
2844
0
    }
2845
0
}
2846
2847
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2848
0
{
2849
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2850
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2851
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2852
0
    ImGuiContext& g = *GImGui;
2853
0
    ImGuiWindow* window = g.CurrentWindow;
2854
0
    float off_y = pos_y - window->DC.CursorPos.y;
2855
0
    window->DC.CursorPos.y = pos_y;
2856
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2857
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2858
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2859
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2860
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2861
0
    if (ImGuiTable* table = g.CurrentTable)
2862
0
    {
2863
0
        if (table->IsInsideRow)
2864
0
            ImGui::TableEndRow(table);
2865
0
        table->RowPosY2 = window->DC.CursorPos.y;
2866
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2867
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2868
0
        table->RowBgColorCounter += row_increase;
2869
0
    }
2870
0
}
2871
2872
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2873
0
{
2874
    // StartPosY starts from ItemsFrozen hence the subtraction
2875
    // Perform the add and multiply with double to allow seeking through larger ranges
2876
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2877
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2878
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2879
0
}
2880
2881
ImGuiListClipper::ImGuiListClipper()
2882
0
{
2883
0
    memset(this, 0, sizeof(*this));
2884
0
}
2885
2886
ImGuiListClipper::~ImGuiListClipper()
2887
0
{
2888
0
    End();
2889
0
}
2890
2891
void ImGuiListClipper::Begin(int items_count, float items_height)
2892
0
{
2893
0
    if (Ctx == NULL)
2894
0
        Ctx = ImGui::GetCurrentContext();
2895
2896
0
    ImGuiContext& g = *Ctx;
2897
0
    ImGuiWindow* window = g.CurrentWindow;
2898
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2899
2900
0
    if (ImGuiTable* table = g.CurrentTable)
2901
0
        if (table->IsInsideRow)
2902
0
            ImGui::TableEndRow(table);
2903
2904
0
    StartPosY = window->DC.CursorPos.y;
2905
0
    ItemsHeight = items_height;
2906
0
    ItemsCount = items_count;
2907
0
    DisplayStart = -1;
2908
0
    DisplayEnd = 0;
2909
2910
    // Acquire temporary buffer
2911
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2912
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2913
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2914
0
    data->Reset(this);
2915
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2916
0
    TempData = data;
2917
0
}
2918
2919
void ImGuiListClipper::End()
2920
0
{
2921
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2922
0
    {
2923
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2924
0
        ImGuiContext& g = *Ctx;
2925
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2926
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2927
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2928
2929
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2930
0
        IM_ASSERT(data->ListClipper == this);
2931
0
        data->StepNo = data->Ranges.Size;
2932
0
        if (--g.ClipperTempDataStacked > 0)
2933
0
        {
2934
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2935
0
            data->ListClipper->TempData = data;
2936
0
        }
2937
0
        TempData = NULL;
2938
0
    }
2939
0
    ItemsCount = -1;
2940
0
}
2941
2942
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2943
0
{
2944
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2945
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2946
0
    IM_ASSERT(item_begin <= item_end);
2947
0
    if (item_begin < item_end)
2948
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2949
0
}
2950
2951
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2952
0
{
2953
0
    ImGuiContext& g = *clipper->Ctx;
2954
0
    ImGuiWindow* window = g.CurrentWindow;
2955
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2956
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2957
2958
0
    ImGuiTable* table = g.CurrentTable;
2959
0
    if (table && table->IsInsideRow)
2960
0
        ImGui::TableEndRow(table);
2961
2962
    // No items
2963
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2964
0
        return false;
2965
2966
    // While we are in frozen row state, keep displaying items one by one, unclipped
2967
    // FIXME: Could be stored as a table-agnostic state.
2968
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2969
0
    {
2970
0
        clipper->DisplayStart = data->ItemsFrozen;
2971
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2972
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2973
0
            data->ItemsFrozen++;
2974
0
        return true;
2975
0
    }
2976
2977
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2978
0
    bool calc_clipping = false;
2979
0
    if (data->StepNo == 0)
2980
0
    {
2981
0
        clipper->StartPosY = window->DC.CursorPos.y;
2982
0
        if (clipper->ItemsHeight <= 0.0f)
2983
0
        {
2984
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2985
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2986
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2987
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2988
0
            data->StepNo = 1;
2989
0
            return true;
2990
0
        }
2991
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2992
0
    }
2993
2994
    // Step 1: Let the clipper infer height from first range
2995
0
    if (clipper->ItemsHeight <= 0.0f)
2996
0
    {
2997
0
        IM_ASSERT(data->StepNo == 1);
2998
0
        if (table)
2999
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3000
3001
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3002
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3003
0
        if (affected_by_floating_point_precision)
3004
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3005
3006
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3007
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3008
0
    }
3009
3010
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3011
0
    const int already_submitted = clipper->DisplayEnd;
3012
0
    if (calc_clipping)
3013
0
    {
3014
0
        if (g.LogEnabled)
3015
0
        {
3016
            // If logging is active, do not perform any clipping
3017
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3018
0
        }
3019
0
        else
3020
0
        {
3021
            // Add range selected to be included for navigation
3022
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3023
0
            if (is_nav_request)
3024
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3025
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3026
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3027
3028
            // Add focused/active item
3029
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3030
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3031
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3032
3033
            // Add visible range
3034
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3035
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3036
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3037
0
        }
3038
3039
        // Convert position ranges to item index ranges
3040
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3041
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3042
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3043
0
        for (ImGuiListClipperRange& range : data->Ranges)
3044
0
            if (range.PosToIndexConvert)
3045
0
            {
3046
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3047
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3048
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3049
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3050
0
                range.PosToIndexConvert = false;
3051
0
            }
3052
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3053
0
    }
3054
3055
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3056
0
    while (data->StepNo < data->Ranges.Size)
3057
0
    {
3058
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3059
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3060
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3061
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3062
0
        data->StepNo++;
3063
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3064
0
            continue;
3065
0
        return true;
3066
0
    }
3067
3068
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3069
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3070
0
    if (clipper->ItemsCount < INT_MAX)
3071
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3072
3073
0
    return false;
3074
0
}
3075
3076
bool ImGuiListClipper::Step()
3077
0
{
3078
0
    ImGuiContext& g = *Ctx;
3079
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3080
0
    bool ret = ImGuiListClipper_StepInternal(this);
3081
0
    if (ret && (DisplayStart == DisplayEnd))
3082
0
        ret = false;
3083
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3084
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3085
0
    if (need_items_height && ItemsHeight > 0.0f)
3086
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3087
0
    if (ret)
3088
0
    {
3089
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3090
0
    }
3091
0
    else
3092
0
    {
3093
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3094
0
        End();
3095
0
    }
3096
0
    return ret;
3097
0
}
3098
3099
//-----------------------------------------------------------------------------
3100
// [SECTION] STYLING
3101
//-----------------------------------------------------------------------------
3102
3103
ImGuiStyle& ImGui::GetStyle()
3104
73.0k
{
3105
73.0k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3106
73.0k
    return GImGui->Style;
3107
73.0k
}
3108
3109
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3110
386k
{
3111
386k
    ImGuiStyle& style = GImGui->Style;
3112
386k
    ImVec4 c = style.Colors[idx];
3113
386k
    c.w *= style.Alpha * alpha_mul;
3114
386k
    return ColorConvertFloat4ToU32(c);
3115
386k
}
3116
3117
ImU32 ImGui::GetColorU32(const ImVec4& col)
3118
0
{
3119
0
    ImGuiStyle& style = GImGui->Style;
3120
0
    ImVec4 c = col;
3121
0
    c.w *= style.Alpha;
3122
0
    return ColorConvertFloat4ToU32(c);
3123
0
}
3124
3125
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3126
0
{
3127
0
    ImGuiStyle& style = GImGui->Style;
3128
0
    return style.Colors[idx];
3129
0
}
3130
3131
ImU32 ImGui::GetColorU32(ImU32 col)
3132
0
{
3133
0
    ImGuiStyle& style = GImGui->Style;
3134
0
    if (style.Alpha >= 1.0f)
3135
0
        return col;
3136
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3137
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3138
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3139
0
}
3140
3141
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3142
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3143
0
{
3144
0
    ImGuiContext& g = *GImGui;
3145
0
    ImGuiColorMod backup;
3146
0
    backup.Col = idx;
3147
0
    backup.BackupValue = g.Style.Colors[idx];
3148
0
    g.ColorStack.push_back(backup);
3149
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3150
0
}
3151
3152
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3153
24.1k
{
3154
24.1k
    ImGuiContext& g = *GImGui;
3155
24.1k
    ImGuiColorMod backup;
3156
24.1k
    backup.Col = idx;
3157
24.1k
    backup.BackupValue = g.Style.Colors[idx];
3158
24.1k
    g.ColorStack.push_back(backup);
3159
24.1k
    g.Style.Colors[idx] = col;
3160
24.1k
}
3161
3162
void ImGui::PopStyleColor(int count)
3163
24.1k
{
3164
24.1k
    ImGuiContext& g = *GImGui;
3165
24.1k
    if (g.ColorStack.Size < count)
3166
0
    {
3167
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3168
0
        count = g.ColorStack.Size;
3169
0
    }
3170
48.3k
    while (count > 0)
3171
24.1k
    {
3172
24.1k
        ImGuiColorMod& backup = g.ColorStack.back();
3173
24.1k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3174
24.1k
        g.ColorStack.pop_back();
3175
24.1k
        count--;
3176
24.1k
    }
3177
24.1k
}
3178
3179
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3180
{
3181
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3182
};
3183
3184
static const ImGuiDataVarInfo GStyleVarInfo[] =
3185
{
3186
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3187
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3188
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3189
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3190
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3191
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3192
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3193
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3194
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3195
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3196
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3197
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3198
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3199
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3200
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3201
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3202
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3203
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3204
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3205
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3206
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3207
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3208
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3209
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabBarBorderSize) },    // ImGuiStyleVar_TabBarBorderSize
3210
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3211
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3212
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3213
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3214
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3215
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DockingSeparatorSize) },   // ImGuiStyleVar_DockingSeparatorSize
3216
};
3217
3218
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3219
48.2k
{
3220
48.2k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3221
48.2k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3222
48.2k
    return &GStyleVarInfo[idx];
3223
48.2k
}
3224
3225
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3226
0
{
3227
0
    ImGuiContext& g = *GImGui;
3228
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3229
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3230
0
    {
3231
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3232
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3233
0
        *pvar = val;
3234
0
        return;
3235
0
    }
3236
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3237
0
}
3238
3239
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3240
24.1k
{
3241
24.1k
    ImGuiContext& g = *GImGui;
3242
24.1k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3243
24.1k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3244
24.1k
    {
3245
24.1k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3246
24.1k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3247
24.1k
        *pvar = val;
3248
24.1k
        return;
3249
24.1k
    }
3250
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3251
0
}
3252
3253
void ImGui::PopStyleVar(int count)
3254
24.1k
{
3255
24.1k
    ImGuiContext& g = *GImGui;
3256
24.1k
    if (g.StyleVarStack.Size < count)
3257
0
    {
3258
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3259
0
        count = g.StyleVarStack.Size;
3260
0
    }
3261
48.2k
    while (count > 0)
3262
24.1k
    {
3263
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3264
24.1k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3265
24.1k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3266
24.1k
        void* data = info->GetVarPtr(&g.Style);
3267
24.1k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3268
24.1k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3269
24.1k
        g.StyleVarStack.pop_back();
3270
24.1k
        count--;
3271
24.1k
    }
3272
24.1k
}
3273
3274
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3275
0
{
3276
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3277
0
    switch (idx)
3278
0
    {
3279
0
    case ImGuiCol_Text: return "Text";
3280
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3281
0
    case ImGuiCol_WindowBg: return "WindowBg";
3282
0
    case ImGuiCol_ChildBg: return "ChildBg";
3283
0
    case ImGuiCol_PopupBg: return "PopupBg";
3284
0
    case ImGuiCol_Border: return "Border";
3285
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3286
0
    case ImGuiCol_FrameBg: return "FrameBg";
3287
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3288
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3289
0
    case ImGuiCol_TitleBg: return "TitleBg";
3290
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3291
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3292
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3293
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3294
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3295
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3296
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3297
0
    case ImGuiCol_CheckMark: return "CheckMark";
3298
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3299
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3300
0
    case ImGuiCol_Button: return "Button";
3301
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3302
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3303
0
    case ImGuiCol_Header: return "Header";
3304
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3305
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3306
0
    case ImGuiCol_Separator: return "Separator";
3307
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3308
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3309
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3310
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3311
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3312
0
    case ImGuiCol_Tab: return "Tab";
3313
0
    case ImGuiCol_TabHovered: return "TabHovered";
3314
0
    case ImGuiCol_TabActive: return "TabActive";
3315
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3316
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3317
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3318
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3319
0
    case ImGuiCol_PlotLines: return "PlotLines";
3320
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3321
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3322
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3323
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3324
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3325
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3326
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3327
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3328
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3329
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3330
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3331
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3332
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3333
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3334
0
    }
3335
0
    IM_ASSERT(0);
3336
0
    return "Unknown";
3337
0
}
3338
3339
3340
//-----------------------------------------------------------------------------
3341
// [SECTION] RENDER HELPERS
3342
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3343
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3344
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3345
//-----------------------------------------------------------------------------
3346
3347
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3348
96.4k
{
3349
96.4k
    const char* text_display_end = text;
3350
96.4k
    if (!text_end)
3351
96.4k
        text_end = (const char*)-1;
3352
3353
867k
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3354
771k
        text_display_end++;
3355
96.4k
    return text_display_end;
3356
96.4k
}
3357
3358
// Internal ImGui functions to render text
3359
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3360
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3361
0
{
3362
0
    ImGuiContext& g = *GImGui;
3363
0
    ImGuiWindow* window = g.CurrentWindow;
3364
3365
    // Hide anything after a '##' string
3366
0
    const char* text_display_end;
3367
0
    if (hide_text_after_hash)
3368
0
    {
3369
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3370
0
    }
3371
0
    else
3372
0
    {
3373
0
        if (!text_end)
3374
0
            text_end = text + strlen(text); // FIXME-OPT
3375
0
        text_display_end = text_end;
3376
0
    }
3377
3378
0
    if (text != text_display_end)
3379
0
    {
3380
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3381
0
        if (g.LogEnabled)
3382
0
            LogRenderedText(&pos, text, text_display_end);
3383
0
    }
3384
0
}
3385
3386
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3387
58
{
3388
58
    ImGuiContext& g = *GImGui;
3389
58
    ImGuiWindow* window = g.CurrentWindow;
3390
3391
58
    if (!text_end)
3392
0
        text_end = text + strlen(text); // FIXME-OPT
3393
3394
58
    if (text != text_end)
3395
58
    {
3396
58
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3397
58
        if (g.LogEnabled)
3398
0
            LogRenderedText(&pos, text, text_end);
3399
58
    }
3400
58
}
3401
3402
// Default clip_rect uses (pos_min,pos_max)
3403
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3404
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3405
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3406
// better advantage of the render function taking size into account for coarse clipping.
3407
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3408
48.2k
{
3409
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3410
48.2k
    ImVec2 pos = pos_min;
3411
48.2k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3412
3413
48.2k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3414
48.2k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3415
48.2k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3416
48.2k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3417
48.2k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3418
3419
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3420
48.2k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3421
48.2k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3422
3423
    // Render
3424
48.2k
    if (need_clipping)
3425
1
    {
3426
1
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3427
1
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3428
1
    }
3429
48.2k
    else
3430
48.2k
    {
3431
48.2k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3432
48.2k
    }
3433
48.2k
}
3434
3435
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3436
48.2k
{
3437
    // Hide anything after a '##' string
3438
48.2k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3439
48.2k
    const int text_len = (int)(text_display_end - text);
3440
48.2k
    if (text_len == 0)
3441
0
        return;
3442
3443
48.2k
    ImGuiContext& g = *GImGui;
3444
48.2k
    ImGuiWindow* window = g.CurrentWindow;
3445
48.2k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3446
48.2k
    if (g.LogEnabled)
3447
0
        LogRenderedText(&pos_min, text, text_display_end);
3448
48.2k
}
3449
3450
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3451
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3452
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3453
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3454
0
{
3455
0
    ImGuiContext& g = *GImGui;
3456
0
    if (text_end_full == NULL)
3457
0
        text_end_full = FindRenderedTextEnd(text);
3458
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3459
3460
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3461
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3462
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3463
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3464
0
    if (text_size.x > pos_max.x - pos_min.x)
3465
0
    {
3466
        // Hello wo...
3467
        // |       |   |
3468
        // min   max   ellipsis_max
3469
        //          <-> this is generally some padding value
3470
3471
0
        const ImFont* font = draw_list->_Data->Font;
3472
0
        const float font_size = draw_list->_Data->FontSize;
3473
0
        const float font_scale = font_size / font->FontSize;
3474
0
        const char* text_end_ellipsis = NULL;
3475
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3476
3477
        // We can now claim the space between pos_max.x and ellipsis_max.x
3478
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3479
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3480
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3481
0
        {
3482
            // Always display at least 1 character if there's no room for character + ellipsis
3483
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3484
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3485
0
        }
3486
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3487
0
        {
3488
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3489
0
            text_end_ellipsis--;
3490
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3491
0
        }
3492
3493
        // Render text, render ellipsis
3494
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3495
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3496
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3497
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3498
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3499
0
    }
3500
0
    else
3501
0
    {
3502
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3503
0
    }
3504
3505
0
    if (g.LogEnabled)
3506
0
        LogRenderedText(&pos_min, text, text_end_full);
3507
0
}
3508
3509
// Render a rectangle shaped with optional rounding and borders
3510
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3511
490
{
3512
490
    ImGuiContext& g = *GImGui;
3513
490
    ImGuiWindow* window = g.CurrentWindow;
3514
490
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3515
490
    const float border_size = g.Style.FrameBorderSize;
3516
490
    if (border && border_size > 0.0f)
3517
490
    {
3518
490
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3519
490
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3520
490
    }
3521
490
}
3522
3523
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3524
0
{
3525
0
    ImGuiContext& g = *GImGui;
3526
0
    ImGuiWindow* window = g.CurrentWindow;
3527
0
    const float border_size = g.Style.FrameBorderSize;
3528
0
    if (border_size > 0.0f)
3529
0
    {
3530
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3531
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3532
0
    }
3533
0
}
3534
3535
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3536
1.33k
{
3537
1.33k
    ImGuiContext& g = *GImGui;
3538
1.33k
    if (id != g.NavId)
3539
678
        return;
3540
658
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3541
65
        return;
3542
593
    ImGuiWindow* window = g.CurrentWindow;
3543
593
    if (window->DC.NavHideHighlightOneFrame)
3544
0
        return;
3545
3546
593
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3547
593
    ImRect display_rect = bb;
3548
593
    display_rect.ClipWith(window->ClipRect);
3549
593
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3550
137
    {
3551
137
        const float THICKNESS = 2.0f;
3552
137
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3553
137
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3554
137
        bool fully_visible = window->ClipRect.Contains(display_rect);
3555
137
        if (!fully_visible)
3556
91
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3557
137
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3558
137
        if (!fully_visible)
3559
91
            window->DrawList->PopClipRect();
3560
137
    }
3561
593
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3562
456
    {
3563
456
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3564
456
    }
3565
593
}
3566
3567
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3568
0
{
3569
0
    ImGuiContext& g = *GImGui;
3570
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3571
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3572
0
    for (ImGuiViewportP* viewport : g.Viewports)
3573
0
    {
3574
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3575
0
        ImVec2 offset, size, uv[4];
3576
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3577
0
            continue;
3578
0
        const ImVec2 pos = base_pos - offset;
3579
0
        const float scale = base_scale * viewport->DpiScale;
3580
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3581
0
            continue;
3582
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3583
0
        ImTextureID tex_id = font_atlas->TexID;
3584
0
        draw_list->PushTextureID(tex_id);
3585
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3586
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3587
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3588
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3589
0
        draw_list->PopTextureID();
3590
0
    }
3591
0
}
3592
3593
//-----------------------------------------------------------------------------
3594
// [SECTION] INITIALIZATION, SHUTDOWN
3595
//-----------------------------------------------------------------------------
3596
3597
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3598
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3599
ImGuiContext* ImGui::GetCurrentContext()
3600
1
{
3601
1
    return GImGui;
3602
1
}
3603
3604
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3605
1
{
3606
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3607
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3608
#else
3609
1
    GImGui = ctx;
3610
1
#endif
3611
1
}
3612
3613
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3614
0
{
3615
0
    GImAllocatorAllocFunc = alloc_func;
3616
0
    GImAllocatorFreeFunc = free_func;
3617
0
    GImAllocatorUserData = user_data;
3618
0
}
3619
3620
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3621
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3622
0
{
3623
0
    *p_alloc_func = GImAllocatorAllocFunc;
3624
0
    *p_free_func = GImAllocatorFreeFunc;
3625
0
    *p_user_data = GImAllocatorUserData;
3626
0
}
3627
3628
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3629
1
{
3630
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3631
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3632
1
    SetCurrentContext(ctx);
3633
1
    Initialize();
3634
1
    if (prev_ctx != NULL)
3635
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3636
1
    return ctx;
3637
1
}
3638
3639
void ImGui::DestroyContext(ImGuiContext* ctx)
3640
0
{
3641
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3642
0
    if (ctx == NULL) //-V1051
3643
0
        ctx = prev_ctx;
3644
0
    SetCurrentContext(ctx);
3645
0
    Shutdown();
3646
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3647
0
    IM_DELETE(ctx);
3648
0
}
3649
3650
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3651
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3652
{
3653
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3654
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3655
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3656
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3657
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3658
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3659
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3660
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3661
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3662
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3663
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3664
};
3665
3666
void ImGui::Initialize()
3667
1
{
3668
1
    ImGuiContext& g = *GImGui;
3669
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3670
3671
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3672
1
    {
3673
1
        ImGuiSettingsHandler ini_handler;
3674
1
        ini_handler.TypeName = "Window";
3675
1
        ini_handler.TypeHash = ImHashStr("Window");
3676
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3677
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3678
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3679
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3680
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3681
1
        AddSettingsHandler(&ini_handler);
3682
1
    }
3683
1
    TableSettingsAddSettingsHandler();
3684
3685
    // Setup default localization table
3686
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3687
3688
    // Setup default platform clipboard/IME handlers.
3689
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3690
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3691
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3692
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3693
3694
    // Create default viewport
3695
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3696
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3697
1
    viewport->Idx = 0;
3698
1
    viewport->PlatformWindowCreated = true;
3699
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3700
1
    g.Viewports.push_back(viewport);
3701
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3702
1
    g.ViewportCreatedCount++;
3703
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3704
3705
1
#ifdef IMGUI_HAS_DOCK
3706
    // Initialize Docking
3707
1
    DockContextInitialize(&g);
3708
1
#endif
3709
3710
1
    g.Initialized = true;
3711
1
}
3712
3713
// This function is merely here to free heap allocations.
3714
void ImGui::Shutdown()
3715
0
{
3716
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3717
0
    ImGuiContext& g = *GImGui;
3718
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3719
0
    {
3720
0
        g.IO.Fonts->Locked = false;
3721
0
        IM_DELETE(g.IO.Fonts);
3722
0
    }
3723
0
    g.IO.Fonts = NULL;
3724
0
    g.DrawListSharedData.TempBuffer.clear();
3725
3726
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3727
0
    if (!g.Initialized)
3728
0
        return;
3729
3730
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3731
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3732
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3733
3734
    // Destroy platform windows
3735
0
    DestroyPlatformWindows();
3736
3737
    // Shutdown extensions
3738
0
    DockContextShutdown(&g);
3739
3740
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3741
3742
    // Clear everything else
3743
0
    g.Windows.clear_delete();
3744
0
    g.WindowsFocusOrder.clear();
3745
0
    g.WindowsTempSortBuffer.clear();
3746
0
    g.CurrentWindow = NULL;
3747
0
    g.CurrentWindowStack.clear();
3748
0
    g.WindowsById.Clear();
3749
0
    g.NavWindow = NULL;
3750
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3751
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3752
0
    g.MovingWindow = NULL;
3753
3754
0
    g.KeysRoutingTable.Clear();
3755
3756
0
    g.ColorStack.clear();
3757
0
    g.StyleVarStack.clear();
3758
0
    g.FontStack.clear();
3759
0
    g.OpenPopupStack.clear();
3760
0
    g.BeginPopupStack.clear();
3761
0
    g.NavTreeNodeStack.clear();
3762
3763
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3764
0
    g.Viewports.clear_delete();
3765
3766
0
    g.TabBars.Clear();
3767
0
    g.CurrentTabBarStack.clear();
3768
0
    g.ShrinkWidthBuffer.clear();
3769
3770
0
    g.ClipperTempData.clear_destruct();
3771
3772
0
    g.Tables.Clear();
3773
0
    g.TablesTempData.clear_destruct();
3774
0
    g.DrawChannelsTempMergeBuffer.clear();
3775
3776
0
    g.ClipboardHandlerData.clear();
3777
0
    g.MenusIdSubmittedThisFrame.clear();
3778
0
    g.InputTextState.ClearFreeMemory();
3779
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3780
3781
0
    g.SettingsWindows.clear();
3782
0
    g.SettingsHandlers.clear();
3783
3784
0
    if (g.LogFile)
3785
0
    {
3786
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3787
0
        if (g.LogFile != stdout)
3788
0
#endif
3789
0
            ImFileClose(g.LogFile);
3790
0
        g.LogFile = NULL;
3791
0
    }
3792
0
    g.LogBuffer.clear();
3793
0
    g.DebugLogBuf.clear();
3794
0
    g.DebugLogIndex.clear();
3795
3796
0
    g.Initialized = false;
3797
0
}
3798
3799
// No specific ordering/dependency support, will see as needed
3800
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3801
0
{
3802
0
    ImGuiContext& g = *ctx;
3803
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3804
0
    g.Hooks.push_back(*hook);
3805
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3806
0
    return g.HookIdNext;
3807
0
}
3808
3809
// Deferred removal, avoiding issue with changing vector while iterating it
3810
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3811
0
{
3812
0
    ImGuiContext& g = *ctx;
3813
0
    IM_ASSERT(hook_id != 0);
3814
0
    for (ImGuiContextHook& hook : g.Hooks)
3815
0
        if (hook.HookId == hook_id)
3816
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3817
0
}
3818
3819
// Call context hooks (used by e.g. test engine)
3820
// We assume a small number of hooks so all stored in same array
3821
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3822
144k
{
3823
144k
    ImGuiContext& g = *ctx;
3824
144k
    for (ImGuiContextHook& hook : g.Hooks)
3825
0
        if (hook.Type == hook_type)
3826
0
            hook.Callback(&g, &hook);
3827
144k
}
3828
3829
3830
//-----------------------------------------------------------------------------
3831
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3832
//-----------------------------------------------------------------------------
3833
3834
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3835
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3836
4
{
3837
4
    memset(this, 0, sizeof(*this));
3838
4
    Ctx = ctx;
3839
4
    Name = ImStrdup(name);
3840
4
    NameBufLen = (int)strlen(name) + 1;
3841
4
    ID = ImHashStr(name);
3842
4
    IDStack.push_back(ID);
3843
4
    ViewportAllowPlatformMonitorExtend = -1;
3844
4
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3845
4
    MoveId = GetID("#MOVE");
3846
4
    TabId = GetID("#TAB");
3847
4
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3848
4
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3849
4
    AutoFitFramesX = AutoFitFramesY = -1;
3850
4
    AutoPosLastDirection = ImGuiDir_None;
3851
4
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3852
4
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3853
4
    LastFrameActive = -1;
3854
4
    LastFrameJustFocused = -1;
3855
4
    LastTimeActive = -1.0f;
3856
4
    FontWindowScale = FontDpiScale = 1.0f;
3857
4
    SettingsOffset = -1;
3858
4
    DockOrder = -1;
3859
4
    DrawList = &DrawListInst;
3860
4
    DrawList->_Data = &Ctx->DrawListSharedData;
3861
4
    DrawList->_OwnerName = Name;
3862
4
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3863
4
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3864
4
}
3865
3866
ImGuiWindow::~ImGuiWindow()
3867
0
{
3868
0
    IM_ASSERT(DrawList == &DrawListInst);
3869
0
    IM_DELETE(Name);
3870
0
    ColumnsStorage.clear_destruct();
3871
0
}
3872
3873
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3874
120k
{
3875
120k
    ImGuiID seed = IDStack.back();
3876
120k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3877
120k
    ImGuiContext& g = *Ctx;
3878
120k
    if (g.DebugHookIdInfo == id)
3879
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3880
120k
    return id;
3881
120k
}
3882
3883
ImGuiID ImGuiWindow::GetID(const void* ptr)
3884
0
{
3885
0
    ImGuiID seed = IDStack.back();
3886
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3887
0
    ImGuiContext& g = *Ctx;
3888
0
    if (g.DebugHookIdInfo == id)
3889
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3890
0
    return id;
3891
0
}
3892
3893
ImGuiID ImGuiWindow::GetID(int n)
3894
23.6k
{
3895
23.6k
    ImGuiID seed = IDStack.back();
3896
23.6k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3897
23.6k
    ImGuiContext& g = *Ctx;
3898
23.6k
    if (g.DebugHookIdInfo == id)
3899
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3900
23.6k
    return id;
3901
23.6k
}
3902
3903
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3904
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3905
0
{
3906
0
    ImGuiID seed = IDStack.back();
3907
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3908
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3909
0
    return id;
3910
0
}
3911
3912
static void SetCurrentWindow(ImGuiWindow* window)
3913
143k
{
3914
143k
    ImGuiContext& g = *GImGui;
3915
143k
    g.CurrentWindow = window;
3916
143k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3917
143k
    if (window)
3918
119k
    {
3919
119k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3920
119k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3921
119k
    }
3922
143k
}
3923
3924
void ImGui::GcCompactTransientMiscBuffers()
3925
0
{
3926
0
    ImGuiContext& g = *GImGui;
3927
0
    g.ItemFlagsStack.clear();
3928
0
    g.GroupStack.clear();
3929
0
    TableGcCompactSettings();
3930
0
}
3931
3932
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3933
// Not freed:
3934
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3935
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3936
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3937
3
{
3938
3
    window->MemoryCompacted = true;
3939
3
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3940
3
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3941
3
    window->IDStack.clear();
3942
3
    window->DrawList->_ClearFreeMemory();
3943
3
    window->DC.ChildWindows.clear();
3944
3
    window->DC.ItemWidthStack.clear();
3945
3
    window->DC.TextWrapPosStack.clear();
3946
3
}
3947
3948
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3949
2
{
3950
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3951
    // The other buffers tends to amortize much faster.
3952
2
    window->MemoryCompacted = false;
3953
2
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3954
2
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3955
2
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3956
2
}
3957
3958
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3959
97
{
3960
97
    ImGuiContext& g = *GImGui;
3961
3962
    // Clear previous active id
3963
97
    if (g.ActiveId != 0)
3964
45
    {
3965
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3966
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3967
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3968
45
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3969
0
        {
3970
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3971
0
            g.MovingWindow = NULL;
3972
0
        }
3973
3974
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3975
        // but since this is currently quite an exception we'll leave it as is.
3976
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3977
45
        if (g.InputTextState.ID == g.ActiveId)
3978
0
            InputTextDeactivateHook(g.ActiveId);
3979
45
    }
3980
3981
    // Set active id
3982
97
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3983
97
    if (g.ActiveIdIsJustActivated)
3984
90
    {
3985
90
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3986
90
        g.ActiveIdTimer = 0.0f;
3987
90
        g.ActiveIdHasBeenPressedBefore = false;
3988
90
        g.ActiveIdHasBeenEditedBefore = false;
3989
90
        g.ActiveIdMouseButton = -1;
3990
90
        if (id != 0)
3991
45
        {
3992
45
            g.LastActiveId = id;
3993
45
            g.LastActiveIdTimer = 0.0f;
3994
45
        }
3995
90
    }
3996
97
    g.ActiveId = id;
3997
97
    g.ActiveIdAllowOverlap = false;
3998
97
    g.ActiveIdNoClearOnFocusLoss = false;
3999
97
    g.ActiveIdWindow = window;
4000
97
    g.ActiveIdHasBeenEditedThisFrame = false;
4001
97
    if (id)
4002
45
    {
4003
45
        g.ActiveIdIsAlive = id;
4004
45
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4005
45
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4006
45
    }
4007
4008
    // Clear declaration of inputs claimed by the widget
4009
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4010
97
    g.ActiveIdUsingNavDirMask = 0x00;
4011
97
    g.ActiveIdUsingAllKeyboardKeys = false;
4012
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4013
    g.ActiveIdUsingNavInputMask = 0x00;
4014
#endif
4015
97
}
4016
4017
void ImGui::ClearActiveID()
4018
52
{
4019
52
    SetActiveID(0, NULL); // g.ActiveId = 0;
4020
52
}
4021
4022
void ImGui::SetHoveredID(ImGuiID id)
4023
94
{
4024
94
    ImGuiContext& g = *GImGui;
4025
94
    g.HoveredId = id;
4026
94
    g.HoveredIdAllowOverlap = false;
4027
94
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4028
25
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4029
94
}
4030
4031
ImGuiID ImGui::GetHoveredID()
4032
0
{
4033
0
    ImGuiContext& g = *GImGui;
4034
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4035
0
}
4036
4037
// This is called by ItemAdd().
4038
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
4039
void ImGui::KeepAliveID(ImGuiID id)
4040
98.6k
{
4041
98.6k
    ImGuiContext& g = *GImGui;
4042
98.6k
    if (g.ActiveId == id)
4043
715
        g.ActiveIdIsAlive = id;
4044
98.6k
    if (g.ActiveIdPreviousFrame == id)
4045
715
        g.ActiveIdPreviousFrameIsAlive = true;
4046
98.6k
}
4047
4048
void ImGui::MarkItemEdited(ImGuiID id)
4049
0
{
4050
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4051
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4052
0
    ImGuiContext& g = *GImGui;
4053
0
    if (g.LockMarkEdited > 0)
4054
0
        return;
4055
0
    if (g.ActiveId == id || g.ActiveId == 0)
4056
0
    {
4057
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4058
0
        g.ActiveIdHasBeenEditedBefore = true;
4059
0
    }
4060
4061
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4062
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4063
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4064
4065
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4066
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4067
0
}
4068
4069
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4070
1.06k
{
4071
    // An active popup disable hovering on other windows (apart from its own children)
4072
    // FIXME-OPT: This could be cached/stored within the window.
4073
1.06k
    ImGuiContext& g = *GImGui;
4074
1.06k
    if (g.NavWindow)
4075
897
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4076
897
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4077
0
            {
4078
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4079
                // NB: The 'else' is important because Modal windows are also Popups.
4080
0
                bool want_inhibit = false;
4081
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4082
0
                    want_inhibit = true;
4083
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4084
0
                    want_inhibit = true;
4085
4086
                // Inhibit hover unless the window is within the stack of our modal/popup
4087
0
                if (want_inhibit)
4088
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4089
0
                        return false;
4090
0
            }
4091
4092
    // Filter by viewport
4093
1.06k
    if (window->Viewport != g.MouseViewport)
4094
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4095
0
            return false;
4096
4097
1.06k
    return true;
4098
1.06k
}
4099
4100
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4101
0
{
4102
0
    ImGuiContext& g = *GImGui;
4103
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4104
0
        return g.Style.HoverDelayNormal;
4105
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4106
0
        return g.Style.HoverDelayShort;
4107
0
    return 0.0f;
4108
0
}
4109
4110
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4111
0
{
4112
    // Allow instance flags to override shared flags
4113
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4114
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4115
0
    return user_flags | shared_flags;
4116
0
}
4117
4118
// This is roughly matching the behavior of internal-facing ItemHoverable()
4119
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4120
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4121
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4122
0
{
4123
0
    ImGuiContext& g = *GImGui;
4124
0
    ImGuiWindow* window = g.CurrentWindow;
4125
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4126
4127
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4128
0
    {
4129
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4130
0
            return false;
4131
0
        if (!IsItemFocused())
4132
0
            return false;
4133
4134
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4135
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4136
0
    }
4137
0
    else
4138
0
    {
4139
        // Test for bounding box overlap, as updated as ItemAdd()
4140
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4141
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4142
0
            return false;
4143
4144
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4145
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4146
4147
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4148
4149
        // Done with rectangle culling so we can perform heavier checks now
4150
        // Test if we are hovering the right window (our window could be behind another window)
4151
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4152
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4153
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4154
        // the test that has been running for a long while.
4155
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4156
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4157
0
                return false;
4158
4159
        // Test if another item is active (e.g. being dragged)
4160
0
        const ImGuiID id = g.LastItemData.ID;
4161
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4162
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4163
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4164
0
                    return false;
4165
4166
        // Test if interactions on this window are blocked by an active popup or modal.
4167
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4168
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4169
0
            return false;
4170
4171
        // Test if the item is disabled
4172
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4173
0
            return false;
4174
4175
        // Special handling for calling after Begin() which represent the title bar or tab.
4176
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4177
        // will never be overwritten so we need to detect the case.
4178
0
        if (id == window->MoveId && window->WriteAccessed)
4179
0
            return false;
4180
4181
        // Test if using AllowOverlap and overlapped
4182
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4183
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4184
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4185
0
                    return false;
4186
0
    }
4187
4188
    // Handle hover delay
4189
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4190
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4191
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4192
0
    {
4193
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4194
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4195
0
            g.HoverItemDelayTimer = 0.0f;
4196
0
        g.HoverItemDelayId = hover_delay_id;
4197
4198
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4199
        // but once unlocked on a given item we also moving.
4200
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4201
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4202
0
            return false;
4203
4204
0
        if (g.HoverItemDelayTimer < delay)
4205
0
            return false;
4206
0
    }
4207
4208
0
    return true;
4209
0
}
4210
4211
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4212
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4213
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4214
// If you used this in your legacy/custom widgets code:
4215
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4216
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4217
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4218
97.0k
{
4219
97.0k
    ImGuiContext& g = *GImGui;
4220
97.0k
    ImGuiWindow* window = g.CurrentWindow;
4221
97.0k
    if (g.HoveredWindow != window)
4222
95.1k
        return false;
4223
1.97k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4224
1.88k
        return false;
4225
4226
94
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4227
0
        return false;
4228
94
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4229
0
        return false;
4230
4231
    // Done with rectangle culling so we can perform heavier checks now.
4232
94
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4233
0
    {
4234
0
        g.HoveredIdDisabled = true;
4235
0
        return false;
4236
0
    }
4237
4238
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4239
    // hover test in widgets code. We could also decide to split this function is two.
4240
94
    if (id != 0)
4241
94
    {
4242
        // Drag source doesn't report as hovered
4243
94
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4244
0
            return false;
4245
4246
94
        SetHoveredID(id);
4247
4248
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4249
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4250
94
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4251
0
        {
4252
0
            g.HoveredIdAllowOverlap = true;
4253
0
            if (g.HoveredIdPreviousFrame != id)
4254
0
                return false;
4255
0
        }
4256
94
    }
4257
4258
    // When disabled we'll return false but still set HoveredId
4259
94
    if (item_flags & ImGuiItemFlags_Disabled)
4260
0
    {
4261
        // Release active id if turning disabled
4262
0
        if (g.ActiveId == id && id != 0)
4263
0
            ClearActiveID();
4264
0
        g.HoveredIdDisabled = true;
4265
0
        return false;
4266
0
    }
4267
4268
94
    if (id != 0)
4269
94
    {
4270
        // [DEBUG] Item Picker tool!
4271
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4272
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4273
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4274
94
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4275
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4276
94
        if (g.DebugItemPickerBreakId == id)
4277
0
            IM_DEBUG_BREAK();
4278
94
    }
4279
4280
94
    if (g.NavDisableMouseHover)
4281
3
        return false;
4282
4283
91
    return true;
4284
94
}
4285
4286
// FIXME: This is inlined/duplicated in ItemAdd()
4287
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4288
0
{
4289
0
    ImGuiContext& g = *GImGui;
4290
0
    ImGuiWindow* window = g.CurrentWindow;
4291
0
    if (!bb.Overlaps(window->ClipRect))
4292
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4293
0
            if (!g.LogEnabled)
4294
0
                return true;
4295
0
    return false;
4296
0
}
4297
4298
// This is also inlined in ItemAdd()
4299
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4300
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4301
71.8k
{
4302
71.8k
    ImGuiContext& g = *GImGui;
4303
71.8k
    g.LastItemData.ID = item_id;
4304
71.8k
    g.LastItemData.InFlags = in_flags;
4305
71.8k
    g.LastItemData.StatusFlags = item_flags;
4306
71.8k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4307
71.8k
}
4308
4309
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4310
0
{
4311
0
    if (wrap_pos_x < 0.0f)
4312
0
        return 0.0f;
4313
4314
0
    ImGuiContext& g = *GImGui;
4315
0
    ImGuiWindow* window = g.CurrentWindow;
4316
0
    if (wrap_pos_x == 0.0f)
4317
0
    {
4318
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4319
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4320
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4321
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4322
        //else
4323
0
        wrap_pos_x = window->WorkRect.Max.x;
4324
0
    }
4325
0
    else if (wrap_pos_x > 0.0f)
4326
0
    {
4327
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4328
0
    }
4329
4330
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4331
0
}
4332
4333
// IM_ALLOC() == ImGui::MemAlloc()
4334
void* ImGui::MemAlloc(size_t size)
4335
1.26k
{
4336
1.26k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4337
1.26k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4338
1.26k
    if (ImGuiContext* ctx = GImGui)
4339
1.26k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4340
1.26k
#endif
4341
1.26k
    return ptr;
4342
1.26k
}
4343
4344
// IM_FREE() == ImGui::MemFree()
4345
void ImGui::MemFree(void* ptr)
4346
1.21k
{
4347
1.21k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4348
1.21k
    if (ptr != NULL)
4349
1.20k
        if (ImGuiContext* ctx = GImGui)
4350
1.20k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4351
1.21k
#endif
4352
1.21k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4353
1.21k
}
4354
4355
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4356
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4357
2.47k
{
4358
2.47k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4359
2.47k
    IM_UNUSED(ptr);
4360
2.47k
    if (entry->FrameCount != frame_count)
4361
49
    {
4362
49
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4363
49
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4364
49
        entry->FrameCount = frame_count;
4365
49
        entry->AllocCount = entry->FreeCount = 0;
4366
49
    }
4367
2.47k
    if (size != (size_t)-1)
4368
1.26k
    {
4369
1.26k
        entry->AllocCount++;
4370
1.26k
        info->TotalAllocCount++;
4371
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4372
1.26k
    }
4373
1.20k
    else
4374
1.20k
    {
4375
1.20k
        entry->FreeCount++;
4376
1.20k
        info->TotalFreeCount++;
4377
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4378
1.20k
    }
4379
2.47k
}
4380
4381
const char* ImGui::GetClipboardText()
4382
0
{
4383
0
    ImGuiContext& g = *GImGui;
4384
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4385
0
}
4386
4387
void ImGui::SetClipboardText(const char* text)
4388
0
{
4389
0
    ImGuiContext& g = *GImGui;
4390
0
    if (g.IO.SetClipboardTextFn)
4391
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4392
0
}
4393
4394
const char* ImGui::GetVersion()
4395
0
{
4396
0
    return IMGUI_VERSION;
4397
0
}
4398
4399
ImGuiIO& ImGui::GetIO()
4400
82.9k
{
4401
82.9k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4402
82.9k
    return GImGui->IO;
4403
82.9k
}
4404
4405
ImGuiPlatformIO& ImGui::GetPlatformIO()
4406
0
{
4407
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4408
0
    return GImGui->PlatformIO;
4409
0
}
4410
4411
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4412
ImDrawData* ImGui::GetDrawData()
4413
24.1k
{
4414
24.1k
    ImGuiContext& g = *GImGui;
4415
24.1k
    ImGuiViewportP* viewport = g.Viewports[0];
4416
24.1k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4417
24.1k
}
4418
4419
double ImGui::GetTime()
4420
553
{
4421
553
    return GImGui->Time;
4422
553
}
4423
4424
int ImGui::GetFrameCount()
4425
0
{
4426
0
    return GImGui->FrameCount;
4427
0
}
4428
4429
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4430
0
{
4431
    // Create the draw list on demand, because they are not frequently used for all viewports
4432
0
    ImGuiContext& g = *GImGui;
4433
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4434
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4435
0
    if (draw_list == NULL)
4436
0
    {
4437
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4438
0
        draw_list->_OwnerName = drawlist_name;
4439
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4440
0
    }
4441
4442
    // Our ImDrawList system requires that there is always a command
4443
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4444
0
    {
4445
0
        draw_list->_ResetForNewFrame();
4446
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4447
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4448
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4449
0
    }
4450
0
    return draw_list;
4451
0
}
4452
4453
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4454
0
{
4455
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4456
0
}
4457
4458
ImDrawList* ImGui::GetBackgroundDrawList()
4459
0
{
4460
0
    ImGuiContext& g = *GImGui;
4461
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4462
0
}
4463
4464
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4465
0
{
4466
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4467
0
}
4468
4469
ImDrawList* ImGui::GetForegroundDrawList()
4470
0
{
4471
0
    ImGuiContext& g = *GImGui;
4472
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4473
0
}
4474
4475
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4476
0
{
4477
0
    return &GImGui->DrawListSharedData;
4478
0
}
4479
4480
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4481
44
{
4482
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4483
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4484
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4485
44
    ImGuiContext& g = *GImGui;
4486
44
    FocusWindow(window);
4487
44
    SetActiveID(window->MoveId, window);
4488
44
    g.NavDisableHighlight = true;
4489
44
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4490
44
    g.ActiveIdNoClearOnFocusLoss = true;
4491
44
    SetActiveIdUsingAllKeyboardKeys();
4492
4493
44
    bool can_move_window = true;
4494
44
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4495
26
        can_move_window = false;
4496
44
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4497
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4498
0
            can_move_window = false;
4499
44
    if (can_move_window)
4500
18
        g.MovingWindow = window;
4501
44
}
4502
4503
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4504
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4505
0
{
4506
0
    ImGuiContext& g = *GImGui;
4507
0
    bool can_undock_node = false;
4508
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4509
0
    {
4510
        // Can undock if:
4511
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4512
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4513
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4514
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4515
0
            can_undock_node = true;
4516
0
    }
4517
4518
0
    const bool clicked = IsMouseClicked(0);
4519
0
    const bool dragging = IsMouseDragging(0);
4520
0
    if (can_undock_node && dragging)
4521
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4522
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4523
0
        StartMouseMovingWindow(window);
4524
0
}
4525
4526
// Handle mouse moving window
4527
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4528
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4529
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4530
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4531
void ImGui::UpdateMouseMovingWindowNewFrame()
4532
24.1k
{
4533
24.1k
    ImGuiContext& g = *GImGui;
4534
24.1k
    if (g.MovingWindow != NULL)
4535
150
    {
4536
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4537
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4538
150
        KeepAliveID(g.ActiveId);
4539
150
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4540
150
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4541
4542
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4543
150
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4544
150
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4545
132
        {
4546
132
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4547
132
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4548
1
            {
4549
1
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4550
1
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4551
0
                {
4552
0
                    moving_window->Viewport->Pos = pos;
4553
0
                    moving_window->Viewport->UpdateWorkRect();
4554
0
                }
4555
1
            }
4556
132
            FocusWindow(g.MovingWindow);
4557
132
        }
4558
18
        else
4559
18
        {
4560
18
            if (!window_disappared)
4561
18
            {
4562
                // Try to merge the window back into the main viewport.
4563
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4564
18
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4565
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4566
4567
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4568
18
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4569
18
                    g.MouseViewport = moving_window->Viewport;
4570
4571
                // Clear the NoInput window flag set by the Viewport system
4572
18
                if (moving_window->Viewport)
4573
18
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4574
18
            }
4575
4576
18
            g.MovingWindow = NULL;
4577
18
            ClearActiveID();
4578
18
        }
4579
150
    }
4580
23.9k
    else
4581
23.9k
    {
4582
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4583
23.9k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4584
549
        {
4585
549
            KeepAliveID(g.ActiveId);
4586
549
            if (!g.IO.MouseDown[0])
4587
26
                ClearActiveID();
4588
549
        }
4589
23.9k
    }
4590
24.1k
}
4591
4592
// Initiate moving window when clicking on empty space or title bar.
4593
// Handle left-click and right-click focus.
4594
void ImGui::UpdateMouseMovingWindowEndFrame()
4595
24.1k
{
4596
24.1k
    ImGuiContext& g = *GImGui;
4597
24.1k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4598
750
        return;
4599
4600
    // Unless we just made a window/popup appear
4601
23.3k
    if (g.NavWindow && g.NavWindow->Appearing)
4602
1
        return;
4603
4604
    // Click on empty space to focus window and start moving
4605
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4606
23.3k
    if (g.IO.MouseClicked[0])
4607
343
    {
4608
        // Handle the edge case of a popup being closed while clicking in its empty space.
4609
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4610
343
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4611
343
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4612
4613
343
        if (root_window != NULL && !is_closed_popup)
4614
44
        {
4615
44
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4616
4617
            // Cancel moving if clicked outside of title bar
4618
44
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4619
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4620
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4621
0
                        g.MovingWindow = NULL;
4622
4623
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4624
44
            if (g.HoveredIdDisabled)
4625
0
                g.MovingWindow = NULL;
4626
44
        }
4627
299
        else if (root_window == NULL && g.NavWindow != NULL)
4628
59
        {
4629
            // Clicking on void disable focus
4630
59
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4631
59
        }
4632
343
    }
4633
4634
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4635
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4636
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4637
23.3k
    if (g.IO.MouseClicked[1])
4638
66
    {
4639
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4640
        // This is where we can trim the popup stack.
4641
66
        ImGuiWindow* modal = GetTopMostPopupModal();
4642
66
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4643
66
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4644
66
    }
4645
23.3k
}
4646
4647
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4648
// Need to keep in sync with SetWindowPos()
4649
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4650
0
{
4651
0
    window->Pos += delta;
4652
0
    window->ClipRect.Translate(delta);
4653
0
    window->OuterRectClipped.Translate(delta);
4654
0
    window->InnerRect.Translate(delta);
4655
0
    window->DC.CursorPos += delta;
4656
0
    window->DC.CursorStartPos += delta;
4657
0
    window->DC.CursorMaxPos += delta;
4658
0
    window->DC.IdealMaxPos += delta;
4659
0
}
4660
4661
static void ScaleWindow(ImGuiWindow* window, float scale)
4662
0
{
4663
0
    ImVec2 origin = window->Viewport->Pos;
4664
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4665
0
    window->Size = ImTrunc(window->Size * scale);
4666
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4667
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4668
0
}
4669
4670
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4671
119k
{
4672
119k
    return (window->Active) && (!window->Hidden);
4673
119k
}
4674
4675
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4676
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4677
24.1k
{
4678
24.1k
    ImGuiContext& g = *GImGui;
4679
24.1k
    ImGuiIO& io = g.IO;
4680
24.1k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4681
4682
    // Find the window hovered by mouse:
4683
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4684
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4685
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4686
24.1k
    bool clear_hovered_windows = false;
4687
24.1k
    FindHoveredWindow();
4688
24.1k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4689
4690
    // Modal windows prevents mouse from hovering behind them.
4691
24.1k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4692
24.1k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4693
0
        clear_hovered_windows = true;
4694
4695
    // Disabled mouse?
4696
24.1k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4697
0
        clear_hovered_windows = true;
4698
4699
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4700
    // won't report hovering nor request capture even while dragging over our windows afterward.
4701
24.1k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4702
24.1k
    const bool has_open_modal = (modal_window != NULL);
4703
24.1k
    int mouse_earliest_down = -1;
4704
24.1k
    bool mouse_any_down = false;
4705
144k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4706
120k
    {
4707
120k
        if (io.MouseClicked[i])
4708
725
        {
4709
725
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4710
725
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4711
725
        }
4712
120k
        mouse_any_down |= io.MouseDown[i];
4713
120k
        if (io.MouseDown[i])
4714
5.34k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4715
3.94k
                mouse_earliest_down = i;
4716
120k
    }
4717
24.1k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4718
24.1k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4719
4720
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4721
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4722
24.1k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4723
24.1k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4724
2.39k
        clear_hovered_windows = true;
4725
4726
24.1k
    if (clear_hovered_windows)
4727
2.39k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4728
4729
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4730
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4731
24.1k
    if (g.WantCaptureMouseNextFrame != -1)
4732
0
    {
4733
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4734
0
    }
4735
24.1k
    else
4736
24.1k
    {
4737
24.1k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4738
24.1k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4739
24.1k
    }
4740
4741
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4742
24.1k
    if (g.WantCaptureKeyboardNextFrame != -1)
4743
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4744
24.1k
    else
4745
24.1k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4746
24.1k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4747
17.2k
        io.WantCaptureKeyboard = true;
4748
4749
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4750
24.1k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4751
24.1k
}
4752
4753
void ImGui::NewFrame()
4754
24.1k
{
4755
24.1k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4756
24.1k
    ImGuiContext& g = *GImGui;
4757
4758
    // Remove pending delete hooks before frame start.
4759
    // This deferred removal avoid issues of removal while iterating the hook vector
4760
24.1k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4761
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4762
0
            g.Hooks.erase(&g.Hooks[n]);
4763
4764
24.1k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4765
4766
    // Check and assert for various common IO and Configuration mistakes
4767
24.1k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4768
24.1k
    ErrorCheckNewFrameSanityChecks();
4769
24.1k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4770
4771
    // Load settings on first frame, save settings when modified (after a delay)
4772
24.1k
    UpdateSettings();
4773
4774
24.1k
    g.Time += g.IO.DeltaTime;
4775
24.1k
    g.WithinFrameScope = true;
4776
24.1k
    g.FrameCount += 1;
4777
24.1k
    g.TooltipOverrideCount = 0;
4778
24.1k
    g.WindowsActiveCount = 0;
4779
24.1k
    g.MenusIdSubmittedThisFrame.resize(0);
4780
4781
    // Calculate frame-rate for the user, as a purely luxurious feature
4782
24.1k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4783
24.1k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4784
24.1k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4785
24.1k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4786
24.1k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4787
4788
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4789
24.1k
    g.InputEventsTrail.resize(0);
4790
24.1k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4791
4792
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4793
24.1k
    UpdateViewportsNewFrame();
4794
4795
    // Setup current font and draw list shared data
4796
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4797
24.1k
    g.IO.Fonts->Locked = true;
4798
24.1k
    SetCurrentFont(GetDefaultFont());
4799
24.1k
    IM_ASSERT(g.Font->IsLoaded());
4800
24.1k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4801
24.1k
    for (ImGuiViewportP* viewport : g.Viewports)
4802
24.1k
        virtual_space.Add(viewport->GetMainRect());
4803
24.1k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4804
24.1k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4805
24.1k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4806
24.1k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4807
24.1k
    if (g.Style.AntiAliasedLines)
4808
24.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4809
24.1k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4810
24.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4811
24.1k
    if (g.Style.AntiAliasedFill)
4812
24.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4813
24.1k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4814
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4815
4816
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4817
24.1k
    for (ImGuiViewportP* viewport : g.Viewports)
4818
24.1k
    {
4819
24.1k
        viewport->DrawData = NULL;
4820
24.1k
        viewport->DrawDataP.Valid = false;
4821
24.1k
    }
4822
4823
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4824
24.1k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4825
16
        KeepAliveID(g.DragDropPayload.SourceId);
4826
4827
    // Update HoveredId data
4828
24.1k
    if (!g.HoveredIdPreviousFrame)
4829
24.0k
        g.HoveredIdTimer = 0.0f;
4830
24.1k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4831
24.0k
        g.HoveredIdNotActiveTimer = 0.0f;
4832
24.1k
    if (g.HoveredId)
4833
94
        g.HoveredIdTimer += g.IO.DeltaTime;
4834
24.1k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4835
94
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4836
24.1k
    g.HoveredIdPreviousFrame = g.HoveredId;
4837
24.1k
    g.HoveredId = 0;
4838
24.1k
    g.HoveredIdAllowOverlap = false;
4839
24.1k
    g.HoveredIdDisabled = false;
4840
4841
    // Clear ActiveID if the item is not alive anymore.
4842
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4843
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4844
24.1k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4845
0
    {
4846
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4847
0
        ClearActiveID();
4848
0
    }
4849
4850
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4851
24.1k
    if (g.ActiveId)
4852
699
        g.ActiveIdTimer += g.IO.DeltaTime;
4853
24.1k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4854
24.1k
    g.ActiveIdPreviousFrame = g.ActiveId;
4855
24.1k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4856
24.1k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4857
24.1k
    g.ActiveIdIsAlive = 0;
4858
24.1k
    g.ActiveIdHasBeenEditedThisFrame = false;
4859
24.1k
    g.ActiveIdPreviousFrameIsAlive = false;
4860
24.1k
    g.ActiveIdIsJustActivated = false;
4861
24.1k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4862
0
        g.TempInputId = 0;
4863
24.1k
    if (g.ActiveId == 0)
4864
23.4k
    {
4865
23.4k
        g.ActiveIdUsingNavDirMask = 0x00;
4866
23.4k
        g.ActiveIdUsingAllKeyboardKeys = false;
4867
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4868
        g.ActiveIdUsingNavInputMask = 0x00;
4869
#endif
4870
23.4k
    }
4871
4872
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4873
    if (g.ActiveId == 0)
4874
        g.ActiveIdUsingNavInputMask = 0;
4875
    else if (g.ActiveIdUsingNavInputMask != 0)
4876
    {
4877
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4878
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4879
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4880
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4881
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4882
            IM_ASSERT(0); // Other values unsupported
4883
    }
4884
#endif
4885
4886
    // Record when we have been stationary as this state is preserved while over same item.
4887
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4888
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4889
24.1k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4890
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4891
24.1k
    else if (g.HoverItemDelayId == 0)
4892
24.1k
        g.HoverItemUnlockedStationaryId = 0;
4893
24.1k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4894
871
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4895
23.2k
    else if (g.HoveredWindow == NULL)
4896
23.1k
        g.HoverWindowUnlockedStationaryId = 0;
4897
4898
    // Update hover delay for IsItemHovered() with delays and tooltips
4899
24.1k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4900
24.1k
    if (g.HoverItemDelayId != 0)
4901
0
    {
4902
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4903
0
        g.HoverItemDelayClearTimer = 0.0f;
4904
0
        g.HoverItemDelayId = 0;
4905
0
    }
4906
24.1k
    else if (g.HoverItemDelayTimer > 0.0f)
4907
0
    {
4908
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4909
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4910
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4911
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4912
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4913
0
    }
4914
4915
    // Drag and drop
4916
24.1k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4917
24.1k
    g.DragDropAcceptIdCurr = 0;
4918
24.1k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4919
24.1k
    g.DragDropWithinSource = false;
4920
24.1k
    g.DragDropWithinTarget = false;
4921
24.1k
    g.DragDropHoldJustPressedId = 0;
4922
4923
    // Close popups on focus lost (currently wip/opt-in)
4924
    //if (g.IO.AppFocusLost)
4925
    //    ClosePopupsExceptModals();
4926
4927
    // Update keyboard input state
4928
24.1k
    UpdateKeyboardInputs();
4929
4930
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4931
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4932
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4933
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4934
4935
    // Update gamepad/keyboard navigation
4936
24.1k
    NavUpdate();
4937
4938
    // Update mouse input state
4939
24.1k
    UpdateMouseInputs();
4940
4941
    // Undocking
4942
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4943
24.1k
    DockContextNewFrameUpdateUndocking(&g);
4944
4945
    // Find hovered window
4946
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4947
24.1k
    UpdateHoveredWindowAndCaptureFlags();
4948
4949
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4950
24.1k
    UpdateMouseMovingWindowNewFrame();
4951
4952
    // Background darkening/whitening
4953
24.1k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4954
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4955
24.1k
    else
4956
24.1k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4957
4958
24.1k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4959
24.1k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4960
4961
    // Platform IME data: reset for the frame
4962
24.1k
    g.PlatformImeDataPrev = g.PlatformImeData;
4963
24.1k
    g.PlatformImeData.WantVisible = false;
4964
4965
    // Mouse wheel scrolling, scale
4966
24.1k
    UpdateMouseWheel();
4967
4968
    // Mark all windows as not visible and compact unused memory.
4969
24.1k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4970
24.1k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4971
24.1k
    for (ImGuiWindow* window : g.Windows)
4972
95.9k
    {
4973
95.9k
        window->WasActive = window->Active;
4974
95.9k
        window->Active = false;
4975
95.9k
        window->WriteAccessed = false;
4976
95.9k
        window->BeginCountPreviousFrame = window->BeginCount;
4977
95.9k
        window->BeginCount = 0;
4978
4979
        // Garbage collect transient buffers of recently unused windows
4980
95.9k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4981
3
            GcCompactTransientWindowBuffers(window);
4982
95.9k
    }
4983
4984
    // Garbage collect transient buffers of recently unused tables
4985
24.1k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4986
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4987
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4988
24.1k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4989
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4990
0
            TableGcCompactTransientBuffers(&table_temp_data);
4991
24.1k
    if (g.GcCompactAll)
4992
0
        GcCompactTransientMiscBuffers();
4993
24.1k
    g.GcCompactAll = false;
4994
4995
    // Closing the focused window restore focus to the first active root window in descending z-order
4996
24.1k
    if (g.NavWindow && !g.NavWindow->WasActive)
4997
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4998
4999
    // No window should be open at the beginning of the frame.
5000
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5001
24.1k
    g.CurrentWindowStack.resize(0);
5002
24.1k
    g.BeginPopupStack.resize(0);
5003
24.1k
    g.ItemFlagsStack.resize(0);
5004
24.1k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
5005
24.1k
    g.GroupStack.resize(0);
5006
5007
    // Docking
5008
24.1k
    DockContextNewFrameUpdateDocking(&g);
5009
5010
    // [DEBUG] Update debug features
5011
24.1k
    UpdateDebugToolItemPicker();
5012
24.1k
    UpdateDebugToolStackQueries();
5013
24.1k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5014
0
        g.DebugLocateId = 0;
5015
24.1k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
5016
0
    {
5017
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
5018
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
5019
0
    }
5020
5021
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5022
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5023
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5024
24.1k
    g.WithinFrameScopeWithImplicitWindow = true;
5025
24.1k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5026
24.1k
    Begin("Debug##Default");
5027
24.1k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5028
5029
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5030
    // allowing to validate correct Begin/End behavior in user code.
5031
24.1k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5032
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5033
24.1k
    else
5034
24.1k
        g.DebugBeginReturnValueCullDepth = -1;
5035
5036
24.1k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5037
24.1k
}
5038
5039
// FIXME: Add a more explicit sort order in the window structure.
5040
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5041
0
{
5042
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5043
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5044
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5045
0
        return d;
5046
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5047
0
        return d;
5048
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5049
0
}
5050
5051
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5052
95.9k
{
5053
95.9k
    out_sorted_windows->push_back(window);
5054
95.9k
    if (window->Active)
5055
47.7k
    {
5056
47.7k
        int count = window->DC.ChildWindows.Size;
5057
47.7k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5058
71.3k
        for (int i = 0; i < count; i++)
5059
23.6k
        {
5060
23.6k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5061
23.6k
            if (child->Active)
5062
23.6k
                AddWindowToSortBuffer(out_sorted_windows, child);
5063
23.6k
        }
5064
47.7k
    }
5065
95.9k
}
5066
5067
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5068
47.7k
{
5069
47.7k
    ImGuiContext& g = *GImGui;
5070
47.7k
    ImGuiViewportP* viewport = window->Viewport;
5071
47.7k
    IM_ASSERT(viewport != NULL);
5072
47.7k
    g.IO.MetricsRenderWindows++;
5073
47.7k
    if (window->DrawList->_Splitter._Count > 1)
5074
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5075
47.7k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5076
47.7k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5077
23.6k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5078
23.6k
            AddWindowToDrawData(child, layer);
5079
47.7k
}
5080
5081
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5082
24.1k
{
5083
24.1k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5084
24.1k
}
5085
5086
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5087
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5088
24.1k
{
5089
24.1k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5090
24.1k
}
5091
5092
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5093
24.1k
{
5094
24.1k
    int n = builder->Layers[0]->Size;
5095
24.1k
    int full_size = n;
5096
48.2k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5097
24.1k
        full_size += builder->Layers[i]->Size;
5098
24.1k
    builder->Layers[0]->resize(full_size);
5099
48.2k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5100
24.1k
    {
5101
24.1k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5102
24.1k
        if (layer->empty())
5103
24.1k
            continue;
5104
8
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5105
8
        n += layer->Size;
5106
8
        layer->resize(0);
5107
8
    }
5108
24.1k
}
5109
5110
static void InitViewportDrawData(ImGuiViewportP* viewport)
5111
24.1k
{
5112
24.1k
    ImGuiIO& io = ImGui::GetIO();
5113
24.1k
    ImDrawData* draw_data = &viewport->DrawDataP;
5114
5115
24.1k
    viewport->DrawData = draw_data; // Make publicly accessible
5116
24.1k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5117
24.1k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5118
24.1k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5119
24.1k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5120
5121
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5122
    // and to allow applications/backends to easily skip rendering.
5123
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5124
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5125
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5126
24.1k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5127
5128
24.1k
    draw_data->Valid = true;
5129
24.1k
    draw_data->CmdListsCount = 0;
5130
24.1k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5131
24.1k
    draw_data->DisplayPos = viewport->Pos;
5132
24.1k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5133
24.1k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5134
24.1k
    draw_data->OwnerViewport = viewport;
5135
24.1k
}
5136
5137
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5138
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5139
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5140
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5141
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5142
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5143
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5144
143k
{
5145
143k
    ImGuiWindow* window = GetCurrentWindow();
5146
143k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5147
143k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5148
143k
}
5149
5150
void ImGui::PopClipRect()
5151
71.8k
{
5152
71.8k
    ImGuiWindow* window = GetCurrentWindow();
5153
71.8k
    window->DrawList->PopClipRect();
5154
71.8k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5155
71.8k
}
5156
5157
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5158
0
{
5159
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5160
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5161
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5162
0
    return window;
5163
0
}
5164
5165
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5166
0
{
5167
0
    if ((col & IM_COL32_A_MASK) == 0)
5168
0
        return;
5169
5170
0
    ImGuiViewportP* viewport = window->Viewport;
5171
0
    ImRect viewport_rect = viewport->GetMainRect();
5172
5173
    // Draw behind window by moving the draw command at the FRONT of the draw list
5174
0
    {
5175
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5176
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5177
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5178
0
        draw_list->ChannelsMerge();
5179
0
        if (draw_list->CmdBuffer.Size == 0)
5180
0
            draw_list->AddDrawCmd();
5181
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5182
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5183
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5184
0
        IM_ASSERT(cmd.ElemCount == 6);
5185
0
        draw_list->CmdBuffer.pop_back();
5186
0
        draw_list->CmdBuffer.push_front(cmd);
5187
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5188
0
        draw_list->PopClipRect();
5189
0
    }
5190
5191
    // Draw over sibling docking nodes in a same docking tree
5192
0
    if (window->RootWindow->DockIsActive)
5193
0
    {
5194
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5195
0
        draw_list->ChannelsMerge();
5196
0
        if (draw_list->CmdBuffer.Size == 0)
5197
0
            draw_list->AddDrawCmd();
5198
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5199
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5200
0
        draw_list->PopClipRect();
5201
0
    }
5202
0
}
5203
5204
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5205
0
{
5206
0
    ImGuiContext& g = *GImGui;
5207
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5208
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5209
0
    {
5210
0
        ImGuiWindow* window = g.Windows[i];
5211
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5212
0
            continue;
5213
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5214
0
            break;
5215
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5216
0
            bottom_most_visible_window = window;
5217
0
    }
5218
0
    return bottom_most_visible_window;
5219
0
}
5220
5221
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5222
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5223
static void ImGui::RenderDimmedBackgrounds()
5224
24.1k
{
5225
24.1k
    ImGuiContext& g = *GImGui;
5226
24.1k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5227
24.1k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5228
24.1k
        return;
5229
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5230
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5231
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5232
0
        return;
5233
5234
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5235
0
    if (dim_bg_for_modal)
5236
0
    {
5237
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5238
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5239
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5240
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5241
0
    }
5242
0
    else if (dim_bg_for_window_list)
5243
0
    {
5244
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5245
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5246
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5247
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5248
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5249
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5250
5251
        // Draw border around CTRL+Tab target window
5252
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5253
0
        ImGuiViewport* viewport = window->Viewport;
5254
0
        float distance = g.FontSize;
5255
0
        ImRect bb = window->Rect();
5256
0
        bb.Expand(distance);
5257
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5258
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5259
0
        window->DrawList->ChannelsMerge();
5260
0
        if (window->DrawList->CmdBuffer.Size == 0)
5261
0
            window->DrawList->AddDrawCmd();
5262
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5263
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5264
0
        window->DrawList->PopClipRect();
5265
0
    }
5266
5267
    // Draw dimming background on _other_ viewports than the ones our windows are in
5268
0
    for (ImGuiViewportP* viewport : g.Viewports)
5269
0
    {
5270
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5271
0
            continue;
5272
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5273
0
            continue;
5274
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5275
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5276
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5277
0
    }
5278
0
}
5279
5280
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5281
void ImGui::EndFrame()
5282
48.2k
{
5283
48.2k
    ImGuiContext& g = *GImGui;
5284
48.2k
    IM_ASSERT(g.Initialized);
5285
5286
    // Don't process EndFrame() multiple times.
5287
48.2k
    if (g.FrameCountEnded == g.FrameCount)
5288
24.1k
        return;
5289
24.1k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5290
5291
24.1k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5292
5293
24.1k
    ErrorCheckEndFrameSanityChecks();
5294
5295
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5296
24.1k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5297
24.1k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5298
0
    {
5299
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5300
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5301
0
        if (viewport == NULL)
5302
0
            viewport = GetMainViewport();
5303
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5304
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5305
        {
5306
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5307
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5308
            viewport->PlatformHandleRaw = NULL;
5309
        }
5310
        else
5311
#endif
5312
0
        {
5313
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5314
0
        }
5315
0
    }
5316
5317
    // Hide implicit/fallback "Debug" window if it hasn't been used
5318
24.1k
    g.WithinFrameScopeWithImplicitWindow = false;
5319
24.1k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5320
24.1k
        g.CurrentWindow->Active = false;
5321
24.1k
    End();
5322
5323
    // Update navigation: CTRL+Tab, wrap-around requests
5324
24.1k
    NavEndFrame();
5325
5326
    // Update docking
5327
24.1k
    DockContextEndFrame(&g);
5328
5329
24.1k
    SetCurrentViewport(NULL, NULL);
5330
5331
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5332
24.1k
    if (g.DragDropActive)
5333
18
    {
5334
18
        bool is_delivered = g.DragDropPayload.Delivery;
5335
18
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5336
18
        if (is_delivered || is_elapsed)
5337
1
            ClearDragDrop();
5338
18
    }
5339
5340
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5341
24.1k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5342
0
    {
5343
0
        g.DragDropWithinSource = true;
5344
0
        SetTooltip("...");
5345
0
        g.DragDropWithinSource = false;
5346
0
    }
5347
5348
    // End frame
5349
24.1k
    g.WithinFrameScope = false;
5350
24.1k
    g.FrameCountEnded = g.FrameCount;
5351
5352
    // Initiate moving window + handle left-click and right-click focus
5353
24.1k
    UpdateMouseMovingWindowEndFrame();
5354
5355
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5356
24.1k
    UpdateViewportsEndFrame();
5357
5358
    // Sort the window list so that all child windows are after their parent
5359
    // We cannot do that on FocusWindow() because children may not exist yet
5360
24.1k
    g.WindowsTempSortBuffer.resize(0);
5361
24.1k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5362
24.1k
    for (ImGuiWindow* window : g.Windows)
5363
95.9k
    {
5364
95.9k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5365
23.6k
            continue;
5366
72.3k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5367
72.3k
    }
5368
5369
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5370
24.1k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5371
24.1k
    g.Windows.swap(g.WindowsTempSortBuffer);
5372
24.1k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5373
5374
    // Unlock font atlas
5375
24.1k
    g.IO.Fonts->Locked = false;
5376
5377
    // Clear Input data for next frame
5378
24.1k
    g.IO.MousePosPrev = g.IO.MousePos;
5379
24.1k
    g.IO.AppFocusLost = false;
5380
24.1k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5381
24.1k
    g.IO.InputQueueCharacters.resize(0);
5382
5383
24.1k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5384
24.1k
}
5385
5386
// Prepare the data for rendering so you can call GetDrawData()
5387
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5388
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5389
void ImGui::Render()
5390
24.1k
{
5391
24.1k
    ImGuiContext& g = *GImGui;
5392
24.1k
    IM_ASSERT(g.Initialized);
5393
5394
24.1k
    if (g.FrameCountEnded != g.FrameCount)
5395
24.1k
        EndFrame();
5396
24.1k
    if (g.FrameCountRendered == g.FrameCount)
5397
0
        return;
5398
24.1k
    g.FrameCountRendered = g.FrameCount;
5399
5400
24.1k
    g.IO.MetricsRenderWindows = 0;
5401
24.1k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5402
5403
    // Add background ImDrawList (for each active viewport)
5404
24.1k
    for (ImGuiViewportP* viewport : g.Viewports)
5405
24.1k
    {
5406
24.1k
        InitViewportDrawData(viewport);
5407
24.1k
        if (viewport->BgFgDrawLists[0] != NULL)
5408
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5409
24.1k
    }
5410
5411
    // Draw modal/window whitening backgrounds
5412
24.1k
    RenderDimmedBackgrounds();
5413
5414
    // Add ImDrawList to render
5415
24.1k
    ImGuiWindow* windows_to_render_top_most[2];
5416
24.1k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5417
24.1k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5418
24.1k
    for (ImGuiWindow* window : g.Windows)
5419
95.9k
    {
5420
95.9k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5421
95.9k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5422
24.1k
            AddRootWindowToDrawData(window);
5423
95.9k
    }
5424
72.3k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5425
48.2k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5426
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5427
5428
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5429
24.1k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5430
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5431
5432
    // Setup ImDrawData structures for end-user
5433
24.1k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5434
24.1k
    for (ImGuiViewportP* viewport : g.Viewports)
5435
24.1k
    {
5436
24.1k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5437
5438
        // Add foreground ImDrawList (for each active viewport)
5439
24.1k
        if (viewport->BgFgDrawLists[1] != NULL)
5440
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5441
5442
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5443
24.1k
        ImDrawData* draw_data = &viewport->DrawDataP;
5444
24.1k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5445
24.1k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5446
47.7k
            draw_list->_PopUnusedDrawCmd();
5447
5448
24.1k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5449
24.1k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5450
24.1k
    }
5451
5452
24.1k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5453
24.1k
}
5454
5455
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5456
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5457
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5458
48.2k
{
5459
48.2k
    ImGuiContext& g = *GImGui;
5460
5461
48.2k
    const char* text_display_end;
5462
48.2k
    if (hide_text_after_double_hash)
5463
48.2k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5464
58
    else
5465
58
        text_display_end = text_end;
5466
5467
48.2k
    ImFont* font = g.Font;
5468
48.2k
    const float font_size = g.FontSize;
5469
48.2k
    if (text == text_display_end)
5470
0
        return ImVec2(0.0f, font_size);
5471
48.2k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5472
5473
    // Round
5474
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5475
    // FIXME: Investigate using ceilf or e.g.
5476
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5477
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5478
48.2k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5479
5480
48.2k
    return text_size;
5481
48.2k
}
5482
5483
// Find window given position, search front-to-back
5484
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5485
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5486
// called, aka before the next Begin(). Moving window isn't affected.
5487
static void FindHoveredWindow()
5488
24.1k
{
5489
24.1k
    ImGuiContext& g = *GImGui;
5490
5491
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5492
24.1k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5493
24.1k
    if (g.MovingWindow)
5494
150
        g.MovingWindow->Viewport = g.MouseViewport;
5495
5496
24.1k
    ImGuiWindow* hovered_window = NULL;
5497
24.1k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5498
24.1k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5499
150
        hovered_window = g.MovingWindow;
5500
5501
24.1k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5502
24.1k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5503
116k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5504
93.7k
    {
5505
93.7k
        ImGuiWindow* window = g.Windows[i];
5506
93.7k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5507
93.7k
        if (!window->Active || window->Hidden)
5508
46.5k
            continue;
5509
47.1k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5510
4
            continue;
5511
47.1k
        IM_ASSERT(window->Viewport);
5512
47.1k
        if (window->Viewport != g.MouseViewport)
5513
0
            continue;
5514
5515
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5516
47.1k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5517
47.1k
        if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5518
46.1k
            continue;
5519
5520
        // Support for one rectangular hole in any given window
5521
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5522
993
        if (window->HitTestHoleSize.x != 0)
5523
0
        {
5524
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5525
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5526
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5527
0
                continue;
5528
0
        }
5529
5530
993
        if (hovered_window == NULL)
5531
851
            hovered_window = window;
5532
993
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5533
993
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5534
851
            hovered_window_ignoring_moving_window = window;
5535
993
        if (hovered_window && hovered_window_ignoring_moving_window)
5536
851
            break;
5537
993
    }
5538
5539
24.1k
    g.HoveredWindow = hovered_window;
5540
24.1k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5541
5542
24.1k
    if (g.MovingWindow)
5543
150
        g.MovingWindow->Viewport = moving_window_viewport;
5544
24.1k
}
5545
5546
bool ImGui::IsItemActive()
5547
41.1k
{
5548
41.1k
    ImGuiContext& g = *GImGui;
5549
41.1k
    if (g.ActiveId)
5550
737
        return g.ActiveId == g.LastItemData.ID;
5551
40.4k
    return false;
5552
41.1k
}
5553
5554
bool ImGui::IsItemActivated()
5555
0
{
5556
0
    ImGuiContext& g = *GImGui;
5557
0
    if (g.ActiveId)
5558
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5559
0
            return true;
5560
0
    return false;
5561
0
}
5562
5563
bool ImGui::IsItemDeactivated()
5564
0
{
5565
0
    ImGuiContext& g = *GImGui;
5566
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5567
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5568
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5569
0
}
5570
5571
bool ImGui::IsItemDeactivatedAfterEdit()
5572
0
{
5573
0
    ImGuiContext& g = *GImGui;
5574
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5575
0
}
5576
5577
// == GetItemID() == GetFocusID()
5578
bool ImGui::IsItemFocused()
5579
0
{
5580
0
    ImGuiContext& g = *GImGui;
5581
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5582
0
        return false;
5583
5584
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5585
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5586
0
    ImGuiWindow* window = g.CurrentWindow;
5587
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5588
0
        return false;
5589
5590
0
    return true;
5591
0
}
5592
5593
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5594
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5595
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5596
0
{
5597
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5598
0
}
5599
5600
bool ImGui::IsItemToggledOpen()
5601
0
{
5602
0
    ImGuiContext& g = *GImGui;
5603
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5604
0
}
5605
5606
bool ImGui::IsItemToggledSelection()
5607
0
{
5608
0
    ImGuiContext& g = *GImGui;
5609
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5610
0
}
5611
5612
bool ImGui::IsAnyItemHovered()
5613
0
{
5614
0
    ImGuiContext& g = *GImGui;
5615
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5616
0
}
5617
5618
bool ImGui::IsAnyItemActive()
5619
0
{
5620
0
    ImGuiContext& g = *GImGui;
5621
0
    return g.ActiveId != 0;
5622
0
}
5623
5624
bool ImGui::IsAnyItemFocused()
5625
0
{
5626
0
    ImGuiContext& g = *GImGui;
5627
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5628
0
}
5629
5630
bool ImGui::IsItemVisible()
5631
0
{
5632
0
    ImGuiContext& g = *GImGui;
5633
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5634
0
}
5635
5636
bool ImGui::IsItemEdited()
5637
0
{
5638
0
    ImGuiContext& g = *GImGui;
5639
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5640
0
}
5641
5642
// Allow next item to be overlapped by subsequent items.
5643
// This works by requiring HoveredId to match for two subsequent frames,
5644
// so if a following items overwrite it our interactions will naturally be disabled.
5645
void ImGui::SetNextItemAllowOverlap()
5646
0
{
5647
0
    ImGuiContext& g = *GImGui;
5648
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5649
0
}
5650
5651
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5652
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5653
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5654
void ImGui::SetItemAllowOverlap()
5655
{
5656
    ImGuiContext& g = *GImGui;
5657
    ImGuiID id = g.LastItemData.ID;
5658
    if (g.HoveredId == id)
5659
        g.HoveredIdAllowOverlap = true;
5660
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5661
        g.ActiveIdAllowOverlap = true;
5662
}
5663
#endif
5664
5665
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5666
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5667
176
{
5668
176
    ImGuiContext& g = *GImGui;
5669
176
    IM_ASSERT(g.ActiveId != 0);
5670
176
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5671
176
    g.ActiveIdUsingAllKeyboardKeys = true;
5672
176
    NavMoveRequestCancel();
5673
176
}
5674
5675
ImGuiID ImGui::GetItemID()
5676
0
{
5677
0
    ImGuiContext& g = *GImGui;
5678
0
    return g.LastItemData.ID;
5679
0
}
5680
5681
ImVec2 ImGui::GetItemRectMin()
5682
0
{
5683
0
    ImGuiContext& g = *GImGui;
5684
0
    return g.LastItemData.Rect.Min;
5685
0
}
5686
5687
ImVec2 ImGui::GetItemRectMax()
5688
0
{
5689
0
    ImGuiContext& g = *GImGui;
5690
0
    return g.LastItemData.Rect.Max;
5691
0
}
5692
5693
ImVec2 ImGui::GetItemRectSize()
5694
0
{
5695
0
    ImGuiContext& g = *GImGui;
5696
0
    return g.LastItemData.Rect.GetSize();
5697
0
}
5698
5699
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5700
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'.
5701
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5702
23.6k
{
5703
23.6k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5704
23.6k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5705
23.6k
}
5706
5707
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5708
0
{
5709
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5710
0
}
5711
5712
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5713
23.6k
{
5714
23.6k
    ImGuiContext& g = *GImGui;
5715
23.6k
    ImGuiWindow* parent_window = g.CurrentWindow;
5716
23.6k
    IM_ASSERT(id != 0);
5717
5718
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5719
23.6k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY;
5720
23.6k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5721
23.6k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5722
23.6k
    if (window_flags & ImGuiWindowFlags_AlwaysAutoResize)
5723
23.6k
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot combine ImGuiChildFlags_ResizeX/ImGuiChildFlags_ResizeY with ImGuiWindowFlags_AlwaysAutoResize.");
5724
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5725
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5726
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5727
#endif
5728
5729
23.6k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5730
23.6k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5731
5732
23.6k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5733
23.6k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5734
5735
    // Forward child flags
5736
23.6k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5737
23.6k
    g.NextWindowData.ChildFlags = child_flags;
5738
5739
    // Forward size
5740
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5741
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5742
23.6k
    const ImVec2 content_avail = GetContentRegionAvail();
5743
23.6k
    ImVec2 size = ImTrunc(size_arg);
5744
23.6k
    if (size.x <= 0.0f)
5745
21.1k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5746
23.6k
    if (size.y <= 0.0f)
5747
21.2k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5748
23.6k
    SetNextWindowSize(size);
5749
5750
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5751
23.6k
    const char* temp_window_name;
5752
23.6k
    if (name && parent_window->IDStack.back() == parent_window->ID)
5753
23.6k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5754
0
    else if (name)
5755
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5756
0
    else
5757
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5758
5759
23.6k
    const float backup_border_size = g.Style.ChildBorderSize;
5760
23.6k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5761
10.8k
        g.Style.ChildBorderSize = 0.0f;
5762
5763
    // Begin into window
5764
23.6k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5765
23.6k
    g.Style.ChildBorderSize = backup_border_size;
5766
5767
23.6k
    ImGuiWindow* child_window = g.CurrentWindow;
5768
23.6k
    child_window->ChildId = id;
5769
5770
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5771
    // While this is not really documented/defined, it seems that the expected thing to do.
5772
23.6k
    if (child_window->BeginCount == 1)
5773
23.6k
        parent_window->DC.CursorPos = child_window->Pos;
5774
5775
    // Process navigation-in immediately so NavInit can run on first frame
5776
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5777
23.6k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5778
23.6k
    if (g.ActiveId == temp_id_for_activation)
5779
0
        ClearActiveID();
5780
23.6k
    if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5781
1
    {
5782
1
        FocusWindow(child_window);
5783
1
        NavInitWindow(child_window, false);
5784
1
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5785
1
        g.ActiveIdSource = g.NavInputSource;
5786
1
    }
5787
23.6k
    return ret;
5788
23.6k
}
5789
5790
void ImGui::EndChild()
5791
23.6k
{
5792
23.6k
    ImGuiContext& g = *GImGui;
5793
23.6k
    ImGuiWindow* child_window = g.CurrentWindow;
5794
5795
23.6k
    IM_ASSERT(g.WithinEndChild == false);
5796
23.6k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5797
5798
23.6k
    g.WithinEndChild = true;
5799
23.6k
    ImVec2 child_size = child_window->Size;
5800
23.6k
    End();
5801
23.6k
    if (child_window->BeginCount == 1)
5802
23.6k
    {
5803
23.6k
        ImGuiWindow* parent_window = g.CurrentWindow;
5804
23.6k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5805
23.6k
        ItemSize(child_size);
5806
23.6k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5807
818
        {
5808
818
            ItemAdd(bb, child_window->ChildId);
5809
818
            RenderNavHighlight(bb, child_window->ChildId);
5810
5811
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5812
818
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5813
518
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5814
818
        }
5815
22.8k
        else
5816
22.8k
        {
5817
            // Not navigable into
5818
22.8k
            ItemAdd(bb, 0);
5819
5820
            // But when flattened we directly reach items, adjust active layer mask accordingly
5821
22.8k
            if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5822
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5823
22.8k
        }
5824
23.6k
        if (g.HoveredWindow == child_window)
5825
529
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5826
23.6k
    }
5827
23.6k
    g.WithinEndChild = false;
5828
23.6k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5829
23.6k
}
5830
5831
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5832
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5833
0
{
5834
0
    ImGuiContext& g = *GImGui;
5835
0
    const ImGuiStyle& style = g.Style;
5836
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5837
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5838
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5839
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5840
0
    bool ret = BeginChild(id, size, ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding, ImGuiWindowFlags_NoMove | extra_flags);
5841
0
    PopStyleVar(3);
5842
0
    PopStyleColor();
5843
0
    return ret;
5844
0
}
5845
5846
void ImGui::EndChildFrame()
5847
0
{
5848
0
    EndChild();
5849
0
}
5850
5851
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5852
50
{
5853
50
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5854
50
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5855
50
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5856
50
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5857
50
}
5858
5859
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5860
71.8k
{
5861
71.8k
    ImGuiContext& g = *GImGui;
5862
71.8k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5863
71.8k
}
5864
5865
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5866
71.8k
{
5867
71.8k
    ImGuiID id = ImHashStr(name);
5868
71.8k
    return FindWindowByID(id);
5869
71.8k
}
5870
5871
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5872
0
{
5873
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5874
0
    window->ViewportPos = main_viewport->Pos;
5875
0
    if (settings->ViewportId)
5876
0
    {
5877
0
        window->ViewportId = settings->ViewportId;
5878
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5879
0
    }
5880
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5881
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5882
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5883
0
    window->Collapsed = settings->Collapsed;
5884
0
    window->DockId = settings->DockId;
5885
0
    window->DockOrder = settings->DockOrder;
5886
0
}
5887
5888
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5889
71.8k
{
5890
71.8k
    ImGuiContext& g = *GImGui;
5891
5892
71.8k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5893
71.8k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5894
71.8k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5895
3
    {
5896
3
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5897
3
        g.WindowsFocusOrder.push_back(window);
5898
3
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5899
3
    }
5900
71.8k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5901
0
    {
5902
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5903
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5904
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5905
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5906
0
        window->FocusOrder = -1;
5907
0
    }
5908
71.8k
    window->IsExplicitChild = new_is_explicit_child;
5909
71.8k
}
5910
5911
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5912
4
{
5913
    // Initial window state with e.g. default/arbitrary window position
5914
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5915
4
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5916
4
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5917
4
    window->Size = window->SizeFull = ImVec2(0, 0);
5918
4
    window->ViewportPos = main_viewport->Pos;
5919
4
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5920
5921
4
    if (settings != NULL)
5922
0
    {
5923
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5924
0
        ApplyWindowSettings(window, settings);
5925
0
    }
5926
4
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5927
5928
4
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5929
1
    {
5930
1
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5931
1
        window->AutoFitOnlyGrows = false;
5932
1
    }
5933
3
    else
5934
3
    {
5935
3
        if (window->Size.x <= 0.0f)
5936
3
            window->AutoFitFramesX = 2;
5937
3
        if (window->Size.y <= 0.0f)
5938
3
            window->AutoFitFramesY = 2;
5939
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5940
3
    }
5941
4
}
5942
5943
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5944
4
{
5945
    // Create window the first time
5946
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5947
4
    ImGuiContext& g = *GImGui;
5948
4
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5949
4
    window->Flags = flags;
5950
4
    g.WindowsById.SetVoidPtr(window->ID, window);
5951
5952
4
    ImGuiWindowSettings* settings = NULL;
5953
4
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5954
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5955
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5956
5957
4
    InitOrLoadWindowSettings(window, settings);
5958
5959
4
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5960
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5961
4
    else
5962
4
        g.Windows.push_back(window);
5963
5964
4
    return window;
5965
4
}
5966
5967
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5968
0
{
5969
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5970
0
}
5971
5972
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5973
144k
{
5974
144k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5975
144k
}
5976
5977
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5978
215k
{
5979
    // Popups, menus and childs bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5980
215k
    ImGuiContext& g = *GImGui;
5981
215k
    ImVec2 size_min;
5982
215k
    if (window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_ChildWindow))
5983
70.8k
    {
5984
70.8k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5985
70.8k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5986
70.8k
    }
5987
144k
    else
5988
144k
    {
5989
144k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5990
144k
        size_min = g.Style.WindowMinSize;
5991
144k
        size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
5992
144k
    }
5993
215k
    return size_min;
5994
215k
}
5995
5996
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5997
143k
{
5998
143k
    ImGuiContext& g = *GImGui;
5999
143k
    ImVec2 new_size = size_desired;
6000
143k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6001
0
    {
6002
        // Using -1,-1 on either X/Y axis to preserve the current size.
6003
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6004
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6005
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6006
0
        if (g.NextWindowData.SizeCallback)
6007
0
        {
6008
0
            ImGuiSizeCallbackData data;
6009
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6010
0
            data.Pos = window->Pos;
6011
0
            data.CurrentSize = window->SizeFull;
6012
0
            data.DesiredSize = new_size;
6013
0
            g.NextWindowData.SizeCallback(&data);
6014
0
            new_size = data.DesiredSize;
6015
0
        }
6016
0
        new_size.x = IM_TRUNC(new_size.x);
6017
0
        new_size.y = IM_TRUNC(new_size.y);
6018
0
    }
6019
6020
    // Minimum size
6021
143k
    ImVec2 size_min = CalcWindowMinSize(window);
6022
143k
    return ImMax(new_size, size_min);
6023
143k
}
6024
6025
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6026
71.8k
{
6027
71.8k
    bool preserve_old_content_sizes = false;
6028
71.8k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6029
490
        preserve_old_content_sizes = true;
6030
71.3k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6031
4
        preserve_old_content_sizes = true;
6032
71.8k
    if (preserve_old_content_sizes)
6033
494
    {
6034
494
        *content_size_current = window->ContentSize;
6035
494
        *content_size_ideal = window->ContentSizeIdeal;
6036
494
        return;
6037
494
    }
6038
6039
71.3k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6040
71.3k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6041
71.3k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6042
71.3k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6043
71.3k
}
6044
6045
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6046
71.8k
{
6047
71.8k
    ImGuiContext& g = *GImGui;
6048
71.8k
    ImGuiStyle& style = g.Style;
6049
71.8k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6050
71.8k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6051
71.8k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6052
71.8k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6053
71.8k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6054
29
    {
6055
        // Tooltip always resize
6056
29
        return size_desired;
6057
29
    }
6058
71.8k
    else
6059
71.8k
    {
6060
        // Maximum window size is determined by the viewport size or monitor size
6061
71.8k
        ImVec2 size_min = CalcWindowMinSize(window);
6062
71.8k
        ImVec2 avail_size = window->Viewport->WorkSize;
6063
71.8k
        if (window->ViewportOwned)
6064
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
6065
71.8k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6066
71.8k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6067
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
6068
71.8k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
6069
6070
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6071
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6072
71.8k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6073
71.8k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6074
71.8k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6075
71.8k
        if (will_have_scrollbar_x)
6076
23.6k
            size_auto_fit.y += style.ScrollbarSize;
6077
71.8k
        if (will_have_scrollbar_y)
6078
1.60k
            size_auto_fit.x += style.ScrollbarSize;
6079
71.8k
        return size_auto_fit;
6080
71.8k
    }
6081
71.8k
}
6082
6083
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6084
0
{
6085
0
    ImVec2 size_contents_current;
6086
0
    ImVec2 size_contents_ideal;
6087
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6088
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6089
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6090
0
    return size_final;
6091
0
}
6092
6093
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6094
71.3k
{
6095
71.3k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6096
29
        return ImGuiCol_PopupBg;
6097
71.3k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6098
23.6k
        return ImGuiCol_ChildBg;
6099
47.7k
    return ImGuiCol_WindowBg;
6100
71.3k
}
6101
6102
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6103
0
{
6104
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6105
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6106
0
    ImVec2 size_expected = pos_max - pos_min;
6107
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6108
0
    *out_pos = pos_min;
6109
0
    if (corner_norm.x == 0.0f)
6110
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6111
0
    if (corner_norm.y == 0.0f)
6112
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6113
0
    *out_size = size_constrained;
6114
0
}
6115
6116
// Data for resizing from resize grip / corner
6117
struct ImGuiResizeGripDef
6118
{
6119
    ImVec2  CornerPosN;
6120
    ImVec2  InnerDir;
6121
    int     AngleMin12, AngleMax12;
6122
};
6123
static const ImGuiResizeGripDef resize_grip_def[4] =
6124
{
6125
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6126
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6127
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6128
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6129
};
6130
6131
// Data for resizing from borders
6132
struct ImGuiResizeBorderDef
6133
{
6134
    ImVec2  InnerDir;               // Normal toward inside
6135
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6136
    float   OuterAngle;             // Angle toward outside
6137
};
6138
static const ImGuiResizeBorderDef resize_border_def[4] =
6139
{
6140
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6141
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6142
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6143
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6144
};
6145
6146
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6147
0
{
6148
0
    ImRect rect = window->Rect();
6149
0
    if (thickness == 0.0f)
6150
0
        rect.Max -= ImVec2(1, 1);
6151
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6152
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6153
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6154
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6155
0
    IM_ASSERT(0);
6156
0
    return ImRect();
6157
0
}
6158
6159
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6160
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6161
0
{
6162
0
    IM_ASSERT(n >= 0 && n < 4);
6163
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6164
0
    id = ImHashStr("#RESIZE", 0, id);
6165
0
    id = ImHashData(&n, sizeof(int), id);
6166
0
    return id;
6167
0
}
6168
6169
// Borders (Left, Right, Up, Down)
6170
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6171
0
{
6172
0
    IM_ASSERT(dir >= 0 && dir < 4);
6173
0
    int n = (int)dir + 4;
6174
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6175
0
    id = ImHashStr("#RESIZE", 0, id);
6176
0
    id = ImHashData(&n, sizeof(int), id);
6177
0
    return id;
6178
0
}
6179
6180
// Handle resize for: Resize Grips, Borders, Gamepad
6181
// Return true when using auto-fit (double-click on resize grip)
6182
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6183
71.3k
{
6184
71.3k
    ImGuiContext& g = *GImGui;
6185
71.3k
    ImGuiWindowFlags flags = window->Flags;
6186
6187
71.3k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6188
23.6k
        return false;
6189
47.7k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6190
24.1k
        return false;
6191
6192
23.6k
    int ret_auto_fit_mask = 0x00;
6193
23.6k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6194
23.6k
    const float grip_hover_inner_size = IM_TRUNC(grip_draw_size * 0.75f);
6195
23.6k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6196
6197
23.6k
    ImRect clamp_rect = visibility_rect;
6198
23.6k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6199
23.6k
    if (window_move_from_title_bar)
6200
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6201
6202
23.6k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6203
23.6k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6204
6205
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6206
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6207
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6208
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6209
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6210
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6211
23.6k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6212
23.6k
    if (clip_with_viewport_rect)
6213
23.6k
        window->ClipRect = window->Viewport->GetMainRect();
6214
6215
    // Resize grips and borders are on layer 1
6216
23.6k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6217
6218
    // Manual resize grips
6219
23.6k
    PushID("#RESIZE");
6220
47.2k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6221
23.6k
    {
6222
23.6k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6223
23.6k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6224
6225
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6226
23.6k
        bool hovered, held;
6227
23.6k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6228
23.6k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6229
23.6k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6230
23.6k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6231
23.6k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6232
23.6k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6233
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6234
23.6k
        if (hovered || held)
6235
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6236
6237
23.6k
        if (held && g.IO.MouseDoubleClicked[0])
6238
0
        {
6239
            // Auto-fit when double-clicking
6240
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6241
0
            ret_auto_fit_mask = 0x03; // Both axises
6242
0
            ClearActiveID();
6243
0
        }
6244
23.6k
        else if (held)
6245
0
        {
6246
            // Resize from any of the four corners
6247
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6248
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6249
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6250
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6251
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6252
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6253
0
        }
6254
6255
        // Only lower-left grip is visible before hovering/activating
6256
23.6k
        if (resize_grip_n == 0 || held || hovered)
6257
23.6k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6258
23.6k
    }
6259
6260
23.6k
    int resize_border_mask = 0x00;
6261
23.6k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6262
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6263
23.6k
    else
6264
23.6k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6265
118k
    for (int border_n = 0; border_n < 4; border_n++)
6266
94.4k
    {
6267
94.4k
        if ((resize_border_mask & (1 << border_n)) == 0)
6268
94.4k
            continue;
6269
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6270
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6271
6272
0
        bool hovered, held;
6273
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6274
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6275
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6276
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6277
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6278
0
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6279
0
            hovered = false;
6280
0
        if (hovered || held)
6281
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6282
0
        if (held && g.IO.MouseDoubleClicked[0])
6283
0
        {
6284
            // Double-clicking bottom or right border auto-fit on this axis
6285
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6286
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6287
0
            {
6288
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6289
0
                ret_auto_fit_mask |= (1 << axis);
6290
0
                hovered = held = false; // So border doesn't show highlighted at new position
6291
0
            }
6292
0
            ClearActiveID();
6293
0
        }
6294
0
        else if (held)
6295
0
        {
6296
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6297
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6298
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6299
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6300
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6301
0
            {
6302
0
                g.WindowResizeBorderExpectedRect = border_rect;
6303
0
                g.WindowResizeRelativeMode = false;
6304
0
            }
6305
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6306
0
                g.WindowResizeRelativeMode = true;
6307
6308
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6309
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6310
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6311
6312
            // Use absolute mode position
6313
0
            ImVec2 border_target = window->Pos;
6314
0
            border_target[axis] = border_target_abs_mode_for_axis;
6315
6316
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6317
0
            bool ignore_resize = false;
6318
0
            if (g.WindowResizeRelativeMode)
6319
0
            {
6320
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6321
0
                border_target[axis] = border_target_rel_mode_for_axis;
6322
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6323
0
                    ignore_resize = true;
6324
0
            }
6325
6326
            // Clamp, apply
6327
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6328
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6329
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6330
0
            if (window->Flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6331
0
                border_target = ImClamp(border_target, window->ParentWindow->InnerClipRect.Min, window->ParentWindow->InnerClipRect.Max);
6332
0
            if (!ignore_resize)
6333
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6334
0
        }
6335
0
        if (hovered)
6336
0
            *border_hovered = border_n;
6337
0
        if (held)
6338
0
            *border_held = border_n;
6339
0
    }
6340
23.6k
    PopID();
6341
6342
    // Restore nav layer
6343
23.6k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6344
6345
    // Navigation resize (keyboard/gamepad)
6346
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6347
    // Not even sure the callback works here.
6348
23.6k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6349
0
    {
6350
0
        ImVec2 nav_resize_dir;
6351
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6352
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6353
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6354
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6355
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6356
0
        {
6357
0
            const float NAV_RESIZE_SPEED = 600.0f;
6358
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6359
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6360
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6361
0
            g.NavWindowingToggleLayer = false;
6362
0
            g.NavDisableMouseHover = true;
6363
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6364
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6365
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6366
0
            {
6367
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6368
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6369
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6370
0
            }
6371
0
        }
6372
0
    }
6373
6374
    // Apply back modified position/size to window
6375
23.6k
    if (size_target.x != FLT_MAX)
6376
0
        window->Size.x = window->SizeFull.x = size_target.x;
6377
23.6k
    if (size_target.y != FLT_MAX)
6378
0
        window->Size.y = window->SizeFull.y = size_target.y;
6379
23.6k
    if (pos_target.x != FLT_MAX)
6380
0
        window->Pos.x = ImTrunc(pos_target.x);
6381
23.6k
    if (pos_target.y != FLT_MAX)
6382
0
        window->Pos.y = ImTrunc(pos_target.y);
6383
23.6k
    if (size_target.x != FLT_MAX || size_target.y != FLT_MAX || pos_target.x != FLT_MAX || pos_target.y != FLT_MAX)
6384
0
        MarkIniSettingsDirty(window);
6385
6386
    // Recalculate next expected border expected coordinates
6387
23.6k
    if (*border_held != -1)
6388
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6389
6390
23.6k
    return ret_auto_fit_mask;
6391
47.7k
}
6392
6393
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6394
48.2k
{
6395
48.2k
    ImGuiContext& g = *GImGui;
6396
48.2k
    ImVec2 size_for_clamping = window->Size;
6397
48.2k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6398
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6399
48.2k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6400
48.2k
}
6401
6402
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6403
71.3k
{
6404
71.3k
    ImGuiContext& g = *GImGui;
6405
71.3k
    float rounding = window->WindowRounding;
6406
71.3k
    float border_size = window->WindowBorderSize;
6407
71.3k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6408
60.5k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6409
6410
71.3k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6411
0
    {
6412
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6413
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6414
0
        const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6415
0
        const ImU32 border_col = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6416
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6417
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6418
0
        window->DrawList->PathStroke(border_col, 0, ImMax(2.0f, border_size)); // Thicker than usual
6419
0
    }
6420
71.3k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6421
0
    {
6422
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6423
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6424
0
    }
6425
71.3k
}
6426
6427
// Draw background and borders
6428
// Draw and handle scrollbars
6429
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6430
71.8k
{
6431
71.8k
    ImGuiContext& g = *GImGui;
6432
71.8k
    ImGuiStyle& style = g.Style;
6433
71.8k
    ImGuiWindowFlags flags = window->Flags;
6434
6435
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6436
71.8k
    IM_ASSERT(window->BeginCount == 0);
6437
71.8k
    window->SkipItems = false;
6438
6439
    // Draw window + handle manual resize
6440
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6441
71.8k
    const float window_rounding = window->WindowRounding;
6442
71.8k
    const float window_border_size = window->WindowBorderSize;
6443
71.8k
    if (window->Collapsed)
6444
490
    {
6445
        // Title bar only
6446
490
        const float backup_border_size = style.FrameBorderSize;
6447
490
        g.Style.FrameBorderSize = window->WindowBorderSize;
6448
490
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6449
490
        if (window->ViewportOwned)
6450
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6451
490
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6452
490
        g.Style.FrameBorderSize = backup_border_size;
6453
490
    }
6454
71.3k
    else
6455
71.3k
    {
6456
        // Window background
6457
71.3k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6458
71.3k
        {
6459
71.3k
            bool is_docking_transparent_payload = false;
6460
71.3k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6461
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6462
0
                    is_docking_transparent_payload = true;
6463
6464
71.3k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6465
71.3k
            if (window->ViewportOwned)
6466
0
            {
6467
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6468
0
                if (is_docking_transparent_payload)
6469
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6470
0
            }
6471
71.3k
            else
6472
71.3k
            {
6473
                // Adjust alpha. For docking
6474
71.3k
                bool override_alpha = false;
6475
71.3k
                float alpha = 1.0f;
6476
71.3k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6477
0
                {
6478
0
                    alpha = g.NextWindowData.BgAlphaVal;
6479
0
                    override_alpha = true;
6480
0
                }
6481
71.3k
                if (is_docking_transparent_payload)
6482
0
                {
6483
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6484
0
                    override_alpha = true;
6485
0
                }
6486
71.3k
                if (override_alpha)
6487
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6488
71.3k
            }
6489
6490
            // Render, for docked windows and host windows we ensure bg goes before decorations
6491
71.3k
            if (window->DockIsActive)
6492
0
                window->DockNode->LastBgColor = bg_col;
6493
71.3k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6494
71.3k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6495
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6496
71.3k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6497
71.3k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6498
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6499
71.3k
        }
6500
71.3k
        if (window->DockIsActive)
6501
0
            window->DockNode->IsBgDrawnThisFrame = true;
6502
6503
        // Title bar
6504
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6505
        // in order for their pos/size to be matching their undocking state.)
6506
71.3k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6507
47.7k
        {
6508
47.7k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6509
47.7k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6510
47.7k
        }
6511
6512
        // Menu bar
6513
71.3k
        if (flags & ImGuiWindowFlags_MenuBar)
6514
0
        {
6515
0
            ImRect menu_bar_rect = window->MenuBarRect();
6516
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6517
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6518
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6519
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6520
0
        }
6521
6522
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6523
71.3k
        ImGuiDockNode* node = window->DockNode;
6524
71.3k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6525
0
        {
6526
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6527
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6528
0
            ImVec2 p = node->Pos;
6529
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6530
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6531
0
            KeepAliveID(unhide_id);
6532
0
            bool hovered, held;
6533
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6534
0
                node->WantHiddenTabBarToggle = true;
6535
0
            else if (held && IsMouseDragging(0))
6536
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6537
6538
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6539
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6540
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6541
0
        }
6542
6543
        // Scrollbars
6544
71.3k
        if (window->ScrollbarX)
6545
23.6k
            Scrollbar(ImGuiAxis_X);
6546
71.3k
        if (window->ScrollbarY)
6547
1.76k
            Scrollbar(ImGuiAxis_Y);
6548
6549
        // Render resize grips (after their input handling so we don't have a frame of latency)
6550
71.3k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6551
47.7k
        {
6552
95.4k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6553
47.7k
            {
6554
47.7k
                const ImU32 col = resize_grip_col[resize_grip_n];
6555
47.7k
                if ((col & IM_COL32_A_MASK) == 0)
6556
24.1k
                    continue;
6557
23.6k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6558
23.6k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6559
23.6k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6560
23.6k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6561
23.6k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6562
23.6k
                window->DrawList->PathFillConvex(col);
6563
23.6k
            }
6564
47.7k
        }
6565
6566
        // Borders (for dock node host they will be rendered over after the tab bar)
6567
71.3k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6568
71.3k
            RenderWindowOuterBorders(window);
6569
71.3k
    }
6570
71.8k
}
6571
6572
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6573
// Render title text, collapse button, close button
6574
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6575
48.2k
{
6576
48.2k
    ImGuiContext& g = *GImGui;
6577
48.2k
    ImGuiStyle& style = g.Style;
6578
48.2k
    ImGuiWindowFlags flags = window->Flags;
6579
6580
48.2k
    const bool has_close_button = (p_open != NULL);
6581
48.2k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6582
6583
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6584
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6585
48.2k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6586
48.2k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6587
48.2k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6588
6589
    // Layout buttons
6590
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6591
48.2k
    float pad_l = style.FramePadding.x;
6592
48.2k
    float pad_r = style.FramePadding.x;
6593
48.2k
    float button_sz = g.FontSize;
6594
48.2k
    ImVec2 close_button_pos;
6595
48.2k
    ImVec2 collapse_button_pos;
6596
48.2k
    if (has_close_button)
6597
0
    {
6598
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6599
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6600
0
    }
6601
48.2k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6602
0
    {
6603
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6604
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6605
0
    }
6606
48.2k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6607
48.2k
    {
6608
48.2k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6609
48.2k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6610
48.2k
    }
6611
6612
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6613
48.2k
    if (has_collapse_button)
6614
48.2k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6615
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6616
6617
    // Close button
6618
48.2k
    if (has_close_button)
6619
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6620
0
            *p_open = false;
6621
6622
48.2k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6623
48.2k
    g.CurrentItemFlags = item_flags_backup;
6624
6625
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6626
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6627
48.2k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6628
48.2k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6629
6630
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6631
    // while uncentered title text will still reach edges correctly.
6632
48.2k
    if (pad_l > style.FramePadding.x)
6633
48.2k
        pad_l += g.Style.ItemInnerSpacing.x;
6634
48.2k
    if (pad_r > style.FramePadding.x)
6635
0
        pad_r += g.Style.ItemInnerSpacing.x;
6636
48.2k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6637
0
    {
6638
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6639
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6640
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6641
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6642
0
    }
6643
6644
48.2k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6645
48.2k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6646
48.2k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6647
0
    {
6648
0
        ImVec2 marker_pos;
6649
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6650
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6651
0
        if (marker_pos.x > layout_r.Min.x)
6652
0
        {
6653
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6654
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6655
0
        }
6656
0
    }
6657
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6658
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6659
48.2k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6660
48.2k
}
6661
6662
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6663
71.8k
{
6664
71.8k
    window->ParentWindow = parent_window;
6665
71.8k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6666
71.8k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6667
23.6k
    {
6668
23.6k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6669
23.6k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6670
23.6k
            window->RootWindow = parent_window->RootWindow;
6671
23.6k
    }
6672
71.8k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6673
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6674
71.8k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6675
23.6k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6676
71.8k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6677
0
    {
6678
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6679
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6680
0
    }
6681
71.8k
}
6682
6683
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6684
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6685
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6686
// - WindowA            // FindBlockingModal() returns Modal1
6687
//   - WindowB          //                  .. returns Modal1
6688
//   - Modal1           //                  .. returns Modal2
6689
//      - WindowC       //                  .. returns Modal2
6690
//          - WindowD   //                  .. returns Modal2
6691
//          - Modal2    //                  .. returns Modal2
6692
//            - WindowE //                  .. returns NULL
6693
// Notes:
6694
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6695
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6696
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6697
61
{
6698
61
    ImGuiContext& g = *GImGui;
6699
61
    if (g.OpenPopupStack.Size <= 0)
6700
61
        return NULL;
6701
6702
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6703
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6704
0
    {
6705
0
        ImGuiWindow* popup_window = popup_data.Window;
6706
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6707
0
            continue;
6708
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6709
0
            continue;
6710
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6711
0
            return popup_window;
6712
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6713
0
            continue;
6714
0
        return popup_window;                                        // Place window right below first block modal
6715
0
    }
6716
0
    return NULL;
6717
0
}
6718
6719
// Push a new Dear ImGui window to add widgets to.
6720
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6721
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6722
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6723
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6724
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6725
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6726
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6727
71.8k
{
6728
71.8k
    ImGuiContext& g = *GImGui;
6729
71.8k
    const ImGuiStyle& style = g.Style;
6730
71.8k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6731
71.8k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6732
71.8k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6733
6734
    // Find or create
6735
71.8k
    ImGuiWindow* window = FindWindowByName(name);
6736
71.8k
    const bool window_just_created = (window == NULL);
6737
71.8k
    if (window_just_created)
6738
4
        window = CreateNewWindow(name, flags);
6739
6740
    // Automatically disable manual moving/resizing when NoInputs is set
6741
71.8k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6742
29
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6743
6744
71.8k
    if (flags & ImGuiWindowFlags_NavFlattened)
6745
71.8k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6746
6747
71.8k
    const int current_frame = g.FrameCount;
6748
71.8k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6749
71.8k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6750
6751
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6752
71.8k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6753
71.8k
    if (flags & ImGuiWindowFlags_Popup)
6754
0
    {
6755
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6756
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6757
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6758
0
    }
6759
6760
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6761
71.8k
    const bool window_was_appearing = window->Appearing;
6762
71.8k
    if (first_begin_of_the_frame)
6763
71.8k
    {
6764
71.8k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6765
71.8k
        window->Appearing = window_just_activated_by_user;
6766
71.8k
        if (window->Appearing)
6767
25
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6768
71.8k
        window->FlagsPreviousFrame = window->Flags;
6769
71.8k
        window->Flags = (ImGuiWindowFlags)flags;
6770
71.8k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6771
71.8k
        window->LastFrameActive = current_frame;
6772
71.8k
        window->LastTimeActive = (float)g.Time;
6773
71.8k
        window->BeginOrderWithinParent = 0;
6774
71.8k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6775
71.8k
    }
6776
0
    else
6777
0
    {
6778
0
        flags = window->Flags;
6779
0
    }
6780
6781
    // Docking
6782
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6783
71.8k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6784
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6785
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6786
71.8k
    if (first_begin_of_the_frame)
6787
71.8k
    {
6788
71.8k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6789
71.8k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6790
71.8k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6791
71.8k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6792
71.8k
        if (has_dock_node || new_auto_dock_node)
6793
0
        {
6794
0
            BeginDocked(window, p_open);
6795
0
            flags = window->Flags;
6796
0
            if (window->DockIsActive)
6797
0
            {
6798
0
                IM_ASSERT(window->DockNode != NULL);
6799
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6800
0
            }
6801
6802
            // Amend the Appearing flag
6803
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6804
0
            {
6805
0
                window->Appearing = true;
6806
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6807
0
            }
6808
0
        }
6809
71.8k
        else
6810
71.8k
        {
6811
71.8k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6812
71.8k
        }
6813
71.8k
    }
6814
6815
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6816
71.8k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6817
71.8k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6818
71.8k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6819
6820
    // We allow window memory to be compacted so recreate the base stack when needed.
6821
71.8k
    if (window->IDStack.Size == 0)
6822
2
        window->IDStack.push_back(window->ID);
6823
6824
    // Add to stack
6825
71.8k
    g.CurrentWindow = window;
6826
71.8k
    ImGuiWindowStackData window_stack_data;
6827
71.8k
    window_stack_data.Window = window;
6828
71.8k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6829
71.8k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6830
71.8k
    g.CurrentWindowStack.push_back(window_stack_data);
6831
71.8k
    if (flags & ImGuiWindowFlags_ChildMenu)
6832
0
        g.BeginMenuCount++;
6833
6834
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6835
71.8k
    if (first_begin_of_the_frame)
6836
71.8k
    {
6837
71.8k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6838
71.8k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6839
71.8k
    }
6840
6841
    // Add to focus scope stack
6842
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6843
71.8k
    PushFocusScope(window->ID);
6844
71.8k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6845
71.8k
    g.CurrentWindow = NULL;
6846
6847
    // Add to popup stack
6848
71.8k
    if (flags & ImGuiWindowFlags_Popup)
6849
0
    {
6850
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6851
0
        popup_ref.Window = window;
6852
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6853
0
        g.BeginPopupStack.push_back(popup_ref);
6854
0
        window->PopupId = popup_ref.PopupId;
6855
0
    }
6856
6857
    // Process SetNextWindow***() calls
6858
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6859
71.8k
    bool window_pos_set_by_api = false;
6860
71.8k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6861
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6862
0
    {
6863
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6864
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6865
0
        {
6866
            // May be processed on the next frame if this is our first frame and we are measuring size
6867
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6868
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6869
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6870
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6871
0
        }
6872
0
        else
6873
0
        {
6874
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6875
0
        }
6876
0
    }
6877
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6878
47.7k
    {
6879
47.7k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6880
47.7k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6881
47.7k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6882
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
6883
47.7k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6884
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
6885
47.7k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6886
47.7k
    }
6887
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6888
0
    {
6889
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6890
0
        {
6891
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6892
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6893
0
        }
6894
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6895
0
        {
6896
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6897
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6898
0
        }
6899
0
    }
6900
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6901
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6902
71.8k
    else if (first_begin_of_the_frame)
6903
71.8k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6904
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6905
0
        window->WindowClass = g.NextWindowData.WindowClass;
6906
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6907
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6908
71.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6909
0
        FocusWindow(window);
6910
71.8k
    if (window->Appearing)
6911
25
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6912
6913
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6914
71.8k
    if (first_begin_of_the_frame)
6915
71.8k
    {
6916
        // Initialize
6917
71.8k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6918
71.8k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6919
71.8k
        window->Active = true;
6920
71.8k
        window->HasCloseButton = (p_open != NULL);
6921
71.8k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6922
71.8k
        window->IDStack.resize(1);
6923
71.8k
        window->DrawList->_ResetForNewFrame();
6924
71.8k
        window->DC.CurrentTableIdx = -1;
6925
71.8k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6926
0
        {
6927
0
            window->DrawList->ChannelsSplit(2);
6928
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6929
0
        }
6930
6931
        // Restore buffer capacity when woken from a compacted state, to avoid
6932
71.8k
        if (window->MemoryCompacted)
6933
2
            GcAwakeTransientWindowBuffers(window);
6934
6935
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6936
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6937
71.8k
        bool window_title_visible_elsewhere = false;
6938
71.8k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6939
0
            window_title_visible_elsewhere = true;
6940
71.8k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6941
0
            window_title_visible_elsewhere = true;
6942
71.8k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6943
0
        {
6944
0
            size_t buf_len = (size_t)window->NameBufLen;
6945
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6946
0
            window->NameBufLen = (int)buf_len;
6947
0
        }
6948
6949
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6950
6951
        // Update contents size from last frame for auto-fitting (or use explicit size)
6952
71.8k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6953
6954
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6955
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6956
        // it has a single usage before this code block and may be set below before it is finally checked.
6957
71.8k
        if (window->HiddenFramesCanSkipItems > 0)
6958
4
            window->HiddenFramesCanSkipItems--;
6959
71.8k
        if (window->HiddenFramesCannotSkipItems > 0)
6960
22
            window->HiddenFramesCannotSkipItems--;
6961
71.8k
        if (window->HiddenFramesForRenderOnly > 0)
6962
0
            window->HiddenFramesForRenderOnly--;
6963
6964
        // Hide new windows for one frame until they calculate their size
6965
71.8k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6966
2
            window->HiddenFramesCannotSkipItems = 1;
6967
6968
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6969
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6970
71.8k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6971
21
        {
6972
21
            window->HiddenFramesCannotSkipItems = 1;
6973
21
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6974
21
            {
6975
21
                if (!window_size_x_set_by_api)
6976
21
                    window->Size.x = window->SizeFull.x = 0.f;
6977
21
                if (!window_size_y_set_by_api)
6978
21
                    window->Size.y = window->SizeFull.y = 0.f;
6979
21
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6980
21
            }
6981
21
        }
6982
6983
        // SELECT VIEWPORT
6984
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6985
6986
71.8k
        WindowSelectViewport(window);
6987
71.8k
        SetCurrentViewport(window, window->Viewport);
6988
71.8k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6989
71.8k
        SetCurrentWindow(window);
6990
71.8k
        flags = window->Flags;
6991
6992
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6993
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6994
6995
71.8k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
6996
23.6k
            window->WindowBorderSize = style.ChildBorderSize;
6997
48.2k
        else
6998
48.2k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6999
71.8k
        window->WindowPadding = style.WindowPadding;
7000
71.8k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7001
10.8k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7002
7003
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7004
71.8k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7005
71.8k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7006
7007
71.8k
        bool use_current_size_for_scrollbar_x = window_just_created;
7008
71.8k
        bool use_current_size_for_scrollbar_y = window_just_created;
7009
7010
        // Collapse window by double-clicking on title bar
7011
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7012
71.8k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7013
48.2k
        {
7014
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7015
48.2k
            ImRect title_bar_rect = window->TitleBarRect();
7016
48.2k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
7017
2
                window->WantCollapseToggle = true;
7018
48.2k
            if (window->WantCollapseToggle)
7019
2
            {
7020
2
                window->Collapsed = !window->Collapsed;
7021
2
                if (!window->Collapsed)
7022
1
                    use_current_size_for_scrollbar_y = true;
7023
2
                MarkIniSettingsDirty(window);
7024
2
            }
7025
48.2k
        }
7026
23.6k
        else
7027
23.6k
        {
7028
23.6k
            window->Collapsed = false;
7029
23.6k
        }
7030
71.8k
        window->WantCollapseToggle = false;
7031
7032
        // SIZE
7033
7034
        // Outer Decoration Sizes
7035
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7036
71.8k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7037
71.8k
        window->DecoOuterSizeX1 = 0.0f;
7038
71.8k
        window->DecoOuterSizeX2 = 0.0f;
7039
71.8k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7040
71.8k
        window->DecoOuterSizeY2 = 0.0f;
7041
71.8k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7042
7043
        // Calculate auto-fit size, handle automatic resize
7044
71.8k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7045
71.8k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7046
29
        {
7047
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7048
29
            if (!window_size_x_set_by_api)
7049
29
            {
7050
29
                window->SizeFull.x = size_auto_fit.x;
7051
29
                use_current_size_for_scrollbar_x = true;
7052
29
            }
7053
29
            if (!window_size_y_set_by_api)
7054
29
            {
7055
29
                window->SizeFull.y = size_auto_fit.y;
7056
29
                use_current_size_for_scrollbar_y = true;
7057
29
            }
7058
29
        }
7059
71.8k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7060
2
        {
7061
            // Auto-fit may only grow window during the first few frames
7062
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7063
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7064
2
            {
7065
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7066
2
                use_current_size_for_scrollbar_x = true;
7067
2
            }
7068
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7069
2
            {
7070
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7071
2
                use_current_size_for_scrollbar_y = true;
7072
2
            }
7073
2
            if (!window->Collapsed)
7074
2
                MarkIniSettingsDirty(window);
7075
2
        }
7076
7077
        // Apply minimum/maximum window size constraints and final size
7078
71.8k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7079
71.8k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7080
7081
        // POSITION
7082
7083
        // Popup latch its initial position, will position itself when it appears next frame
7084
71.8k
        if (window_just_activated_by_user)
7085
25
        {
7086
25
            window->AutoPosLastDirection = ImGuiDir_None;
7087
25
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7088
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7089
25
        }
7090
7091
        // Position child window
7092
71.8k
        if (flags & ImGuiWindowFlags_ChildWindow)
7093
23.6k
        {
7094
23.6k
            IM_ASSERT(parent_window && parent_window->Active);
7095
23.6k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7096
23.6k
            parent_window->DC.ChildWindows.push_back(window);
7097
23.6k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7098
23.6k
                window->Pos = parent_window->DC.CursorPos;
7099
23.6k
        }
7100
7101
71.8k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7102
71.8k
        if (window_pos_with_pivot)
7103
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7104
71.8k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7105
0
            window->Pos = FindBestWindowPosForPopup(window);
7106
71.8k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7107
0
            window->Pos = FindBestWindowPosForPopup(window);
7108
71.8k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7109
29
            window->Pos = FindBestWindowPosForPopup(window);
7110
7111
        // Late create viewport if we don't fit within our current host viewport.
7112
71.8k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7113
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7114
0
            {
7115
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7116
                //ImGuiViewport* old_viewport = window->Viewport;
7117
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7118
7119
                // FIXME-DPI
7120
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7121
0
                SetCurrentViewport(window, window->Viewport);
7122
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7123
0
                SetCurrentWindow(window);
7124
0
            }
7125
7126
71.8k
        if (window->ViewportOwned)
7127
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7128
7129
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7130
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7131
71.8k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7132
71.8k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7133
71.8k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7134
71.8k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7135
7136
        // Clamp position/size so window stays visible within its viewport or monitor
7137
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7138
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7139
71.8k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7140
48.2k
        {
7141
48.2k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7142
48.2k
            {
7143
48.2k
                ClampWindowPos(window, visibility_rect);
7144
48.2k
            }
7145
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7146
0
            {
7147
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7148
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7149
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
7150
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
7151
0
                ClampWindowPos(window, visibility_rect);
7152
0
            }
7153
48.2k
        }
7154
71.8k
        window->Pos = ImTrunc(window->Pos);
7155
7156
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7157
        // Large values tend to lead to variety of artifacts and are not recommended.
7158
71.8k
        if (window->ViewportOwned || window->DockIsActive)
7159
0
            window->WindowRounding = 0.0f;
7160
71.8k
        else
7161
71.8k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7162
7163
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7164
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7165
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7166
7167
        // Apply window focus (new and reactivated windows are moved to front)
7168
71.8k
        bool want_focus = false;
7169
71.8k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7170
25
        {
7171
25
            if (flags & ImGuiWindowFlags_Popup)
7172
0
                want_focus = true;
7173
25
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7174
2
                want_focus = true;
7175
25
        }
7176
7177
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7178
#ifdef IMGUI_ENABLE_TEST_ENGINE
7179
        if (g.TestEngineHookItems)
7180
        {
7181
            IM_ASSERT(window->IDStack.Size == 1);
7182
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7183
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7184
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7185
            window->IDStack.Size = 1;
7186
        }
7187
#endif
7188
7189
        // Decide if we are going to handle borders and resize grips
7190
71.8k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7191
7192
        // Handle manual resize: Resize Grips, Borders, Gamepad
7193
71.8k
        int border_hovered = -1, border_held = -1;
7194
71.8k
        ImU32 resize_grip_col[4] = {};
7195
71.8k
        const int resize_grip_count = (window->Flags & ImGuiWindowFlags_ChildWindow) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7196
71.8k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7197
71.8k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7198
71.3k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7199
0
            {
7200
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7201
0
                    use_current_size_for_scrollbar_x = true;
7202
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7203
0
                    use_current_size_for_scrollbar_y = true;
7204
0
            }
7205
71.8k
        window->ResizeBorderHovered = (signed char)border_hovered;
7206
71.8k
        window->ResizeBorderHeld = (signed char)border_held;
7207
7208
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7209
71.8k
        if (window->ViewportOwned)
7210
0
        {
7211
0
            if (!window->Viewport->PlatformRequestMove)
7212
0
                window->Viewport->Pos = window->Pos;
7213
0
            if (!window->Viewport->PlatformRequestResize)
7214
0
                window->Viewport->Size = window->Size;
7215
0
            window->Viewport->UpdateWorkRect();
7216
0
            viewport_rect = window->Viewport->GetMainRect();
7217
0
        }
7218
7219
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7220
71.8k
        window->ViewportPos = window->Viewport->Pos;
7221
7222
        // SCROLLBAR VISIBILITY
7223
7224
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7225
71.8k
        if (!window->Collapsed)
7226
71.3k
        {
7227
            // When reading the current size we need to read it after size constraints have been applied.
7228
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7229
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7230
71.3k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7231
71.3k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7232
71.3k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7233
71.3k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7234
71.3k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7235
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7236
71.3k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7237
71.3k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7238
71.3k
            if (window->ScrollbarX && !window->ScrollbarY)
7239
22.9k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7240
71.3k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7241
7242
            // Amend the partially filled window->DecorationXXX values.
7243
71.3k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7244
71.3k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7245
71.3k
        }
7246
7247
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7248
        // Update various regions. Variables they depend on should be set above in this function.
7249
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7250
7251
        // Outer rectangle
7252
        // Not affected by window border size. Used by:
7253
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7254
        // - Begin() initial clipping rect for drawing window background and borders.
7255
        // - Begin() clipping whole child
7256
71.8k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7257
71.8k
        const ImRect outer_rect = window->Rect();
7258
71.8k
        const ImRect title_bar_rect = window->TitleBarRect();
7259
71.8k
        window->OuterRectClipped = outer_rect;
7260
71.8k
        if (window->DockIsActive)
7261
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7262
71.8k
        window->OuterRectClipped.ClipWith(host_rect);
7263
7264
        // Inner rectangle
7265
        // Not affected by window border size. Used by:
7266
        // - InnerClipRect
7267
        // - ScrollToRectEx()
7268
        // - NavUpdatePageUpPageDown()
7269
        // - Scrollbar()
7270
71.8k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7271
71.8k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7272
71.8k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7273
71.8k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7274
7275
        // Inner clipping rectangle.
7276
        // Will extend a little bit outside the normal work region.
7277
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7278
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7279
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7280
        // Affected by window/frame border size. Used by:
7281
        // - Begin() initial clip rect
7282
71.8k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7283
71.8k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7284
71.8k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7285
71.8k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7286
71.8k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7287
71.8k
        window->InnerClipRect.ClipWithFull(host_rect);
7288
7289
        // Default item width. Make it proportional to window size if window manually resizes
7290
71.8k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7291
71.8k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7292
29
        else
7293
29
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7294
7295
        // SCROLLING
7296
7297
        // Lock down maximum scrolling
7298
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7299
        // for right/bottom aligned items without creating a scrollbar.
7300
71.8k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7301
71.8k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7302
7303
        // Apply scrolling
7304
71.8k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7305
71.8k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7306
71.8k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7307
7308
        // DRAWING
7309
7310
        // Setup draw list and outer clipping rectangle
7311
71.8k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7312
71.8k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7313
71.8k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7314
7315
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7316
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7317
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7318
71.8k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7319
71.8k
        if (is_undocked_or_docked_visible)
7320
71.8k
        {
7321
71.8k
            bool render_decorations_in_parent = false;
7322
71.8k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7323
23.6k
            {
7324
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7325
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7326
23.6k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7327
23.6k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7328
23.6k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7329
23.6k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7330
23.6k
                    render_decorations_in_parent = true;
7331
23.6k
            }
7332
71.8k
            if (render_decorations_in_parent)
7333
23.6k
                window->DrawList = parent_window->DrawList;
7334
7335
            // Handle title bar, scrollbar, resize grips and resize borders
7336
71.8k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7337
71.8k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7338
71.8k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7339
7340
71.8k
            if (render_decorations_in_parent)
7341
23.6k
                window->DrawList = &window->DrawListInst;
7342
71.8k
        }
7343
7344
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7345
7346
        // Work rectangle.
7347
        // Affected by window padding and border size. Used by:
7348
        // - Columns() for right-most edge
7349
        // - TreeNode(), CollapsingHeader() for right-most edge
7350
        // - BeginTabBar() for right-most edge
7351
71.8k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7352
71.8k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7353
71.8k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7354
71.8k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7355
71.8k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7356
71.8k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7357
71.8k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7358
71.8k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7359
71.8k
        window->ParentWorkRect = window->WorkRect;
7360
7361
        // [LEGACY] Content Region
7362
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7363
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7364
        // Used by:
7365
        // - Mouse wheel scrolling + many other things
7366
71.8k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7367
71.8k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7368
71.8k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7369
71.8k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7370
7371
        // Setup drawing context
7372
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7373
71.8k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7374
71.8k
        window->DC.GroupOffset.x = 0.0f;
7375
71.8k
        window->DC.ColumnsOffset.x = 0.0f;
7376
7377
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7378
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7379
71.8k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7380
71.8k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7381
71.8k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7382
71.8k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7383
71.8k
        window->DC.CursorPos = window->DC.CursorStartPos;
7384
71.8k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7385
71.8k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7386
71.8k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7387
71.8k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7388
71.8k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7389
71.8k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7390
7391
71.8k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7392
71.8k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7393
71.8k
        window->DC.NavLayersActiveMaskNext = 0x00;
7394
71.8k
        window->DC.NavIsScrollPushableX = true;
7395
71.8k
        window->DC.NavHideHighlightOneFrame = false;
7396
71.8k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7397
7398
71.8k
        window->DC.MenuBarAppending = false;
7399
71.8k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7400
71.8k
        window->DC.TreeDepth = 0;
7401
71.8k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7402
71.8k
        window->DC.ChildWindows.resize(0);
7403
71.8k
        window->DC.StateStorage = &window->StateStorage;
7404
71.8k
        window->DC.CurrentColumns = NULL;
7405
71.8k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7406
71.8k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7407
7408
71.8k
        window->DC.ItemWidth = window->ItemWidthDefault;
7409
71.8k
        window->DC.TextWrapPos = -1.0f; // disabled
7410
71.8k
        window->DC.ItemWidthStack.resize(0);
7411
71.8k
        window->DC.TextWrapPosStack.resize(0);
7412
7413
71.8k
        if (window->AutoFitFramesX > 0)
7414
4
            window->AutoFitFramesX--;
7415
71.8k
        if (window->AutoFitFramesY > 0)
7416
4
            window->AutoFitFramesY--;
7417
7418
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7419
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7420
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7421
        // - Position window behind the modal that is not a begin-parent of this window.
7422
71.8k
        if (want_focus)
7423
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7424
71.8k
        if (want_focus && window == g.NavWindow)
7425
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7426
7427
        // Close requested by platform window (apply to all windows in this viewport)
7428
71.8k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7429
0
        {
7430
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7431
0
            *p_open = false;
7432
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7433
0
        }
7434
7435
        // Title bar
7436
71.8k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7437
48.2k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7438
7439
        // Clear hit test shape every frame
7440
71.8k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7441
7442
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7443
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7444
        // Maybe we can support CTRL+C on every element?
7445
        /*
7446
        //if (g.NavWindow == window && g.ActiveId == 0)
7447
        if (g.ActiveId == window->MoveId)
7448
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7449
                LogToClipboard();
7450
        */
7451
7452
71.8k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7453
71.8k
        {
7454
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7455
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7456
71.8k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7457
132
                BeginDockableDragDropSource(window);
7458
7459
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7460
71.8k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7461
35
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7462
19
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7463
19
                        BeginDockableDragDropTarget(window);
7464
71.8k
        }
7465
7466
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7467
        // This is useful to allow creating context menus on title bar only, etc.
7468
71.8k
        if (window->DockIsActive)
7469
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7470
71.8k
        else
7471
71.8k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7472
7473
        // [DEBUG]
7474
71.8k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7475
71.8k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7476
0
            DebugLocateItemResolveWithLastItem();
7477
71.8k
#endif
7478
7479
        // [Test Engine] Register title bar / tab with MoveId.
7480
#ifdef IMGUI_ENABLE_TEST_ENGINE
7481
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7482
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7483
#endif
7484
71.8k
    }
7485
0
    else
7486
0
    {
7487
        // Append
7488
0
        SetCurrentViewport(window, window->Viewport);
7489
0
        SetCurrentWindow(window);
7490
0
    }
7491
7492
71.8k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7493
71.8k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7494
7495
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7496
71.8k
    window->WriteAccessed = false;
7497
71.8k
    window->BeginCount++;
7498
71.8k
    g.NextWindowData.ClearFlags();
7499
7500
    // Update visibility
7501
71.8k
    if (first_begin_of_the_frame)
7502
71.8k
    {
7503
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7504
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7505
        // This is analogous to regular windows being hidden from one frame.
7506
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7507
71.8k
        if (window->DockIsActive && !window->DockTabIsVisible)
7508
0
        {
7509
0
            if (window->LastFrameJustFocused == g.FrameCount)
7510
0
                window->HiddenFramesCannotSkipItems = 1;
7511
0
            else
7512
0
                window->HiddenFramesCanSkipItems = 1;
7513
0
        }
7514
7515
71.8k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7516
23.6k
        {
7517
            // Child window can be out of sight and have "negative" clip windows.
7518
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7519
23.6k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7520
23.6k
            const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7521
23.6k
            if (!g.LogEnabled && !nav_request)
7522
23.6k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7523
4
                    window->HiddenFramesCanSkipItems = 1;
7524
7525
            // Hide along with parent or if parent is collapsed
7526
23.6k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7527
0
                window->HiddenFramesCanSkipItems = 1;
7528
23.6k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7529
1
                window->HiddenFramesCannotSkipItems = 1;
7530
23.6k
        }
7531
7532
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7533
71.8k
        if (style.Alpha <= 0.0f)
7534
0
            window->HiddenFramesCanSkipItems = 1;
7535
7536
        // Update the Hidden flag
7537
71.8k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7538
71.8k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7539
7540
        // Disable inputs for requested number of frames
7541
71.8k
        if (window->DisableInputsFrames > 0)
7542
0
        {
7543
0
            window->DisableInputsFrames--;
7544
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7545
0
        }
7546
7547
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7548
71.8k
        bool skip_items = false;
7549
71.8k
        if (window->Collapsed || !window->Active || hidden_regular)
7550
517
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7551
494
                skip_items = true;
7552
71.8k
        window->SkipItems = skip_items;
7553
7554
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7555
71.8k
        if (window->SkipItems)
7556
494
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7557
7558
        // Sanity check: there are two spots which can set Appearing = true
7559
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7560
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7561
71.8k
        if (window->SkipItems && !window->Appearing)
7562
71.8k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7563
71.8k
    }
7564
7565
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7566
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7567
71.8k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7568
0
    {
7569
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7570
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7571
0
        return false;
7572
0
    }
7573
7574
71.8k
    return !window->SkipItems;
7575
71.8k
}
7576
7577
void ImGui::End()
7578
71.8k
{
7579
71.8k
    ImGuiContext& g = *GImGui;
7580
71.8k
    ImGuiWindow* window = g.CurrentWindow;
7581
7582
    // Error checking: verify that user hasn't called End() too many times!
7583
71.8k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7584
0
    {
7585
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7586
0
        return;
7587
0
    }
7588
71.8k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7589
7590
    // Error checking: verify that user doesn't directly call End() on a child window.
7591
71.8k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7592
71.8k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7593
7594
    // Close anything that is open
7595
71.8k
    if (window->DC.CurrentColumns)
7596
0
        EndColumns();
7597
71.8k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7598
71.8k
        PopClipRect();
7599
71.8k
    PopFocusScope();
7600
7601
    // Stop logging
7602
71.8k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7603
48.2k
        LogFinish();
7604
7605
71.8k
    if (window->DC.IsSetPos)
7606
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7607
7608
    // Docking: report contents sizes to parent to allow for auto-resize
7609
71.8k
    if (window->DockNode && window->DockTabIsVisible)
7610
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7611
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7612
7613
    // Pop from window stack
7614
71.8k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7615
71.8k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7616
0
        g.BeginMenuCount--;
7617
71.8k
    if (window->Flags & ImGuiWindowFlags_Popup)
7618
0
        g.BeginPopupStack.pop_back();
7619
71.8k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7620
71.8k
    g.CurrentWindowStack.pop_back();
7621
71.8k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7622
71.8k
    if (g.CurrentWindow)
7623
47.7k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7624
71.8k
}
7625
7626
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7627
10.7k
{
7628
10.7k
    ImGuiContext& g = *GImGui;
7629
10.7k
    IM_ASSERT(window == window->RootWindow);
7630
7631
10.7k
    const int cur_order = window->FocusOrder;
7632
10.7k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7633
10.7k
    if (g.WindowsFocusOrder.back() == window)
7634
10.7k
        return;
7635
7636
1
    const int new_order = g.WindowsFocusOrder.Size - 1;
7637
2
    for (int n = cur_order; n < new_order; n++)
7638
1
    {
7639
1
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7640
1
        g.WindowsFocusOrder[n]->FocusOrder--;
7641
1
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7642
1
    }
7643
1
    g.WindowsFocusOrder[new_order] = window;
7644
1
    window->FocusOrder = (short)new_order;
7645
1
}
7646
7647
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7648
10.7k
{
7649
10.7k
    ImGuiContext& g = *GImGui;
7650
10.7k
    ImGuiWindow* current_front_window = g.Windows.back();
7651
10.7k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7652
10.7k
        return;
7653
2
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7654
2
        if (g.Windows[i] == window)
7655
1
        {
7656
1
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7657
1
            g.Windows[g.Windows.Size - 1] = window;
7658
1
            break;
7659
1
        }
7660
1
}
7661
7662
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7663
0
{
7664
0
    ImGuiContext& g = *GImGui;
7665
0
    if (g.Windows[0] == window)
7666
0
        return;
7667
0
    for (int i = 0; i < g.Windows.Size; i++)
7668
0
        if (g.Windows[i] == window)
7669
0
        {
7670
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7671
0
            g.Windows[0] = window;
7672
0
            break;
7673
0
        }
7674
0
}
7675
7676
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7677
0
{
7678
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7679
0
    ImGuiContext& g = *GImGui;
7680
0
    window = window->RootWindow;
7681
0
    behind_window = behind_window->RootWindow;
7682
0
    int pos_wnd = FindWindowDisplayIndex(window);
7683
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7684
0
    if (pos_wnd < pos_beh)
7685
0
    {
7686
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7687
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7688
0
        g.Windows[pos_beh - 1] = window;
7689
0
    }
7690
0
    else
7691
0
    {
7692
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7693
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7694
0
        g.Windows[pos_beh] = window;
7695
0
    }
7696
0
}
7697
7698
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7699
0
{
7700
0
    ImGuiContext& g = *GImGui;
7701
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7702
0
}
7703
7704
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7705
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7706
16.0k
{
7707
16.0k
    ImGuiContext& g = *GImGui;
7708
7709
    // Modal check?
7710
16.0k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7711
61
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7712
0
        {
7713
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7714
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7715
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7716
0
            return;
7717
0
        }
7718
7719
    // Find last focused child (if any) and focus it instead.
7720
16.0k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7721
0
        window = NavRestoreLastChildNavWindow(window);
7722
7723
    // Apply focus
7724
16.0k
    if (g.NavWindow != window)
7725
5.90k
    {
7726
5.90k
        SetNavWindow(window);
7727
5.90k
        if (window && g.NavDisableMouseHover)
7728
1.12k
            g.NavMousePosDirty = true;
7729
5.90k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7730
5.90k
        g.NavLayer = ImGuiNavLayer_Main;
7731
5.90k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7732
5.90k
        g.NavIdIsAlive = false;
7733
5.90k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7734
7735
        // Close popups if any
7736
5.90k
        ClosePopupsOverWindow(window, false);
7737
5.90k
    }
7738
7739
    // Move the root window to the top of the pile
7740
16.0k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7741
16.0k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7742
16.0k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7743
16.0k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7744
16.0k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7745
7746
    // Steal active widgets. Some of the cases it triggers includes:
7747
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7748
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7749
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7750
16.0k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7751
26
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7752
1
            ClearActiveID();
7753
7754
    // Passing NULL allow to disable keyboard focus
7755
16.0k
    if (!window)
7756
5.27k
        return;
7757
10.7k
    window->LastFrameJustFocused = g.FrameCount;
7758
7759
    // Select in dock node
7760
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
7761
    //if (dock_node && dock_node->TabBar)
7762
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7763
7764
    // Bring to front
7765
10.7k
    BringWindowToFocusFront(focus_front_window);
7766
10.7k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7767
10.7k
        BringWindowToDisplayFront(display_front_window);
7768
10.7k
}
7769
7770
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7771
0
{
7772
0
    ImGuiContext& g = *GImGui;
7773
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7774
0
    if (under_this_window != NULL)
7775
0
    {
7776
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7777
0
        int offset = -1;
7778
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7779
0
        {
7780
0
            under_this_window = under_this_window->ParentWindow;
7781
0
            offset = 0;
7782
0
        }
7783
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7784
0
    }
7785
0
    for (int i = start_idx; i >= 0; i--)
7786
0
    {
7787
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7788
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7789
0
        if (window == ignore_window || !window->WasActive)
7790
0
            continue;
7791
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7792
0
            continue;
7793
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7794
0
        {
7795
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7796
            // This is failing (lagging by one frame) for docked windows.
7797
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7798
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7799
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7800
0
            FocusWindow(window, flags);
7801
0
            return;
7802
0
        }
7803
0
    }
7804
0
    FocusWindow(NULL, flags);
7805
0
}
7806
7807
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7808
void ImGui::SetCurrentFont(ImFont* font)
7809
24.1k
{
7810
24.1k
    ImGuiContext& g = *GImGui;
7811
24.1k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7812
24.1k
    IM_ASSERT(font->Scale > 0.0f);
7813
24.1k
    g.Font = font;
7814
24.1k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7815
24.1k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7816
7817
24.1k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7818
24.1k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7819
24.1k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7820
24.1k
    g.DrawListSharedData.Font = g.Font;
7821
24.1k
    g.DrawListSharedData.FontSize = g.FontSize;
7822
24.1k
}
7823
7824
void ImGui::PushFont(ImFont* font)
7825
0
{
7826
0
    ImGuiContext& g = *GImGui;
7827
0
    if (!font)
7828
0
        font = GetDefaultFont();
7829
0
    SetCurrentFont(font);
7830
0
    g.FontStack.push_back(font);
7831
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7832
0
}
7833
7834
void  ImGui::PopFont()
7835
0
{
7836
0
    ImGuiContext& g = *GImGui;
7837
0
    g.CurrentWindow->DrawList->PopTextureID();
7838
0
    g.FontStack.pop_back();
7839
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7840
0
}
7841
7842
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7843
23.6k
{
7844
23.6k
    ImGuiContext& g = *GImGui;
7845
23.6k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7846
23.6k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7847
23.6k
    if (enabled)
7848
0
        item_flags |= option;
7849
23.6k
    else
7850
23.6k
        item_flags &= ~option;
7851
23.6k
    g.CurrentItemFlags = item_flags;
7852
23.6k
    g.ItemFlagsStack.push_back(item_flags);
7853
23.6k
}
7854
7855
void ImGui::PopItemFlag()
7856
23.6k
{
7857
23.6k
    ImGuiContext& g = *GImGui;
7858
23.6k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7859
23.6k
    g.ItemFlagsStack.pop_back();
7860
23.6k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7861
23.6k
}
7862
7863
// BeginDisabled()/EndDisabled()
7864
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7865
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7866
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7867
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7868
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7869
void ImGui::BeginDisabled(bool disabled)
7870
0
{
7871
0
    ImGuiContext& g = *GImGui;
7872
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7873
0
    if (!was_disabled && disabled)
7874
0
    {
7875
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7876
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7877
0
    }
7878
0
    if (was_disabled || disabled)
7879
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7880
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7881
0
    g.DisabledStackSize++;
7882
0
}
7883
7884
void ImGui::EndDisabled()
7885
0
{
7886
0
    ImGuiContext& g = *GImGui;
7887
0
    IM_ASSERT(g.DisabledStackSize > 0);
7888
0
    g.DisabledStackSize--;
7889
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7890
    //PopItemFlag();
7891
0
    g.ItemFlagsStack.pop_back();
7892
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7893
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7894
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7895
0
}
7896
7897
void ImGui::PushTabStop(bool tab_stop)
7898
23.6k
{
7899
23.6k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7900
23.6k
}
7901
7902
void ImGui::PopTabStop()
7903
23.6k
{
7904
23.6k
    PopItemFlag();
7905
23.6k
}
7906
7907
void ImGui::PushButtonRepeat(bool repeat)
7908
0
{
7909
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7910
0
}
7911
7912
void ImGui::PopButtonRepeat()
7913
0
{
7914
0
    PopItemFlag();
7915
0
}
7916
7917
void ImGui::PushTextWrapPos(float wrap_pos_x)
7918
0
{
7919
0
    ImGuiWindow* window = GetCurrentWindow();
7920
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7921
0
    window->DC.TextWrapPos = wrap_pos_x;
7922
0
}
7923
7924
void ImGui::PopTextWrapPos()
7925
0
{
7926
0
    ImGuiWindow* window = GetCurrentWindow();
7927
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7928
0
    window->DC.TextWrapPosStack.pop_back();
7929
0
}
7930
7931
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7932
0
{
7933
0
    ImGuiWindow* last_window = NULL;
7934
0
    while (last_window != window)
7935
0
    {
7936
0
        last_window = window;
7937
0
        window = window->RootWindow;
7938
0
        if (popup_hierarchy)
7939
0
            window = window->RootWindowPopupTree;
7940
0
    if (dock_hierarchy)
7941
0
      window = window->RootWindowDockTree;
7942
0
  }
7943
0
    return window;
7944
0
}
7945
7946
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7947
0
{
7948
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7949
0
    if (window_root == potential_parent)
7950
0
        return true;
7951
0
    while (window != NULL)
7952
0
    {
7953
0
        if (window == potential_parent)
7954
0
            return true;
7955
0
        if (window == window_root) // end of chain
7956
0
            return false;
7957
0
        window = window->ParentWindow;
7958
0
    }
7959
0
    return false;
7960
0
}
7961
7962
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7963
0
{
7964
0
    if (window->RootWindow == potential_parent)
7965
0
        return true;
7966
0
    while (window != NULL)
7967
0
    {
7968
0
        if (window == potential_parent)
7969
0
            return true;
7970
0
        window = window->ParentWindowInBeginStack;
7971
0
    }
7972
0
    return false;
7973
0
}
7974
7975
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7976
0
{
7977
0
    ImGuiContext& g = *GImGui;
7978
7979
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7980
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7981
0
    if (display_layer_delta != 0)
7982
0
        return display_layer_delta > 0;
7983
7984
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7985
0
    {
7986
0
        ImGuiWindow* candidate_window = g.Windows[i];
7987
0
        if (candidate_window == potential_above)
7988
0
            return true;
7989
0
        if (candidate_window == potential_below)
7990
0
            return false;
7991
0
    }
7992
0
    return false;
7993
0
}
7994
7995
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7996
36.7k
{
7997
36.7k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
7998
7999
36.7k
    ImGuiContext& g = *GImGui;
8000
36.7k
    ImGuiWindow* ref_window = g.HoveredWindow;
8001
36.7k
    ImGuiWindow* cur_window = g.CurrentWindow;
8002
36.7k
    if (ref_window == NULL)
8003
35.1k
        return false;
8004
8005
1.57k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8006
1.57k
    {
8007
1.57k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8008
1.57k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8009
1.57k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8010
1.57k
        if (flags & ImGuiHoveredFlags_RootWindow)
8011
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8012
8013
1.57k
        bool result;
8014
1.57k
        if (flags & ImGuiHoveredFlags_ChildWindows)
8015
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8016
1.57k
        else
8017
1.57k
            result = (ref_window == cur_window);
8018
1.57k
        if (!result)
8019
596
            return false;
8020
1.57k
    }
8021
8022
974
    if (!IsWindowContentHoverable(ref_window, flags))
8023
0
        return false;
8024
974
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8025
974
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8026
0
            return false;
8027
8028
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8029
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8030
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8031
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8032
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8033
974
    if (flags & ImGuiHoveredFlags_ForTooltip)
8034
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8035
974
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8036
0
        return false;
8037
8038
974
    return true;
8039
974
}
8040
8041
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8042
46.9k
{
8043
46.9k
    ImGuiContext& g = *GImGui;
8044
46.9k
    ImGuiWindow* ref_window = g.NavWindow;
8045
46.9k
    ImGuiWindow* cur_window = g.CurrentWindow;
8046
8047
46.9k
    if (ref_window == NULL)
8048
12.7k
        return false;
8049
34.1k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8050
0
        return true;
8051
8052
34.1k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8053
34.1k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8054
34.1k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8055
34.1k
    if (flags & ImGuiHoveredFlags_RootWindow)
8056
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8057
8058
34.1k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8059
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8060
34.1k
    else
8061
34.1k
        return (ref_window == cur_window);
8062
34.1k
}
8063
8064
ImGuiID ImGui::GetWindowDockID()
8065
0
{
8066
0
    ImGuiContext& g = *GImGui;
8067
0
    return g.CurrentWindow->DockId;
8068
0
}
8069
8070
bool ImGui::IsWindowDocked()
8071
0
{
8072
0
    ImGuiContext& g = *GImGui;
8073
0
    return g.CurrentWindow->DockIsActive;
8074
0
}
8075
8076
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8077
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8078
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8079
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8080
0
{
8081
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8082
0
}
8083
8084
float ImGui::GetWindowWidth()
8085
10.3k
{
8086
10.3k
    ImGuiWindow* window = GImGui->CurrentWindow;
8087
10.3k
    return window->Size.x;
8088
10.3k
}
8089
8090
float ImGui::GetWindowHeight()
8091
10.4k
{
8092
10.4k
    ImGuiWindow* window = GImGui->CurrentWindow;
8093
10.4k
    return window->Size.y;
8094
10.4k
}
8095
8096
ImVec2 ImGui::GetWindowPos()
8097
0
{
8098
0
    ImGuiContext& g = *GImGui;
8099
0
    ImGuiWindow* window = g.CurrentWindow;
8100
0
    return window->Pos;
8101
0
}
8102
8103
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8104
1
{
8105
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8106
1
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8107
0
        return;
8108
8109
1
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8110
1
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8111
1
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8112
8113
    // Set
8114
1
    const ImVec2 old_pos = window->Pos;
8115
1
    window->Pos = ImTrunc(pos);
8116
1
    ImVec2 offset = window->Pos - old_pos;
8117
1
    if (offset.x == 0.0f && offset.y == 0.0f)
8118
0
        return;
8119
1
    MarkIniSettingsDirty(window);
8120
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8121
1
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8122
1
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8123
1
    window->DC.IdealMaxPos += offset;
8124
1
    window->DC.CursorStartPos += offset;
8125
1
}
8126
8127
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8128
0
{
8129
0
    ImGuiWindow* window = GetCurrentWindowRead();
8130
0
    SetWindowPos(window, pos, cond);
8131
0
}
8132
8133
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8134
0
{
8135
0
    if (ImGuiWindow* window = FindWindowByName(name))
8136
0
        SetWindowPos(window, pos, cond);
8137
0
}
8138
8139
ImVec2 ImGui::GetWindowSize()
8140
0
{
8141
0
    ImGuiWindow* window = GetCurrentWindowRead();
8142
0
    return window->Size;
8143
0
}
8144
8145
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8146
47.7k
{
8147
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8148
47.7k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8149
24.1k
        return;
8150
8151
23.6k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8152
23.6k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8153
8154
    // Set
8155
23.6k
    ImVec2 old_size = window->SizeFull;
8156
23.6k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8157
23.6k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8158
23.6k
    if (size.x <= 0.0f)
8159
0
        window->AutoFitOnlyGrows = false;
8160
23.6k
    else
8161
23.6k
        window->SizeFull.x = IM_TRUNC(size.x);
8162
23.6k
    if (size.y <= 0.0f)
8163
0
        window->AutoFitOnlyGrows = false;
8164
23.6k
    else
8165
23.6k
        window->SizeFull.y = IM_TRUNC(size.y);
8166
23.6k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8167
4.67k
        MarkIniSettingsDirty(window);
8168
23.6k
}
8169
8170
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8171
0
{
8172
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8173
0
}
8174
8175
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8176
0
{
8177
0
    if (ImGuiWindow* window = FindWindowByName(name))
8178
0
        SetWindowSize(window, size, cond);
8179
0
}
8180
8181
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8182
0
{
8183
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8184
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8185
0
        return;
8186
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8187
8188
    // Set
8189
0
    window->Collapsed = collapsed;
8190
0
}
8191
8192
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8193
0
{
8194
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8195
0
    window->HitTestHoleSize = ImVec2ih(size);
8196
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8197
0
}
8198
8199
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8200
0
{
8201
0
    window->Hidden = window->SkipItems = true;
8202
0
    window->HiddenFramesCanSkipItems = 1;
8203
0
}
8204
8205
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8206
0
{
8207
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8208
0
}
8209
8210
bool ImGui::IsWindowCollapsed()
8211
0
{
8212
0
    ImGuiWindow* window = GetCurrentWindowRead();
8213
0
    return window->Collapsed;
8214
0
}
8215
8216
bool ImGui::IsWindowAppearing()
8217
0
{
8218
0
    ImGuiWindow* window = GetCurrentWindowRead();
8219
0
    return window->Appearing;
8220
0
}
8221
8222
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8223
0
{
8224
0
    if (ImGuiWindow* window = FindWindowByName(name))
8225
0
        SetWindowCollapsed(window, collapsed, cond);
8226
0
}
8227
8228
void ImGui::SetWindowFocus()
8229
10.3k
{
8230
10.3k
    FocusWindow(GImGui->CurrentWindow);
8231
10.3k
}
8232
8233
void ImGui::SetWindowFocus(const char* name)
8234
0
{
8235
0
    if (name)
8236
0
    {
8237
0
        if (ImGuiWindow* window = FindWindowByName(name))
8238
0
            FocusWindow(window);
8239
0
    }
8240
0
    else
8241
0
    {
8242
0
        FocusWindow(NULL);
8243
0
    }
8244
0
}
8245
8246
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8247
0
{
8248
0
    ImGuiContext& g = *GImGui;
8249
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8250
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8251
0
    g.NextWindowData.PosVal = pos;
8252
0
    g.NextWindowData.PosPivotVal = pivot;
8253
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8254
0
    g.NextWindowData.PosUndock = true;
8255
0
}
8256
8257
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8258
47.7k
{
8259
47.7k
    ImGuiContext& g = *GImGui;
8260
47.7k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8261
47.7k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8262
47.7k
    g.NextWindowData.SizeVal = size;
8263
47.7k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8264
47.7k
}
8265
8266
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8267
0
{
8268
0
    ImGuiContext& g = *GImGui;
8269
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8270
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8271
0
    g.NextWindowData.SizeCallback = custom_callback;
8272
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8273
0
}
8274
8275
// Content size = inner scrollable rectangle, padded with WindowPadding.
8276
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8277
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8278
0
{
8279
0
    ImGuiContext& g = *GImGui;
8280
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8281
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8282
0
}
8283
8284
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8285
0
{
8286
0
    ImGuiContext& g = *GImGui;
8287
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8288
0
    g.NextWindowData.ScrollVal = scroll;
8289
0
}
8290
8291
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8292
0
{
8293
0
    ImGuiContext& g = *GImGui;
8294
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8295
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8296
0
    g.NextWindowData.CollapsedVal = collapsed;
8297
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8298
0
}
8299
8300
void ImGui::SetNextWindowFocus()
8301
0
{
8302
0
    ImGuiContext& g = *GImGui;
8303
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8304
0
}
8305
8306
void ImGui::SetNextWindowBgAlpha(float alpha)
8307
0
{
8308
0
    ImGuiContext& g = *GImGui;
8309
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8310
0
    g.NextWindowData.BgAlphaVal = alpha;
8311
0
}
8312
8313
void ImGui::SetNextWindowViewport(ImGuiID id)
8314
0
{
8315
0
    ImGuiContext& g = *GImGui;
8316
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8317
0
    g.NextWindowData.ViewportId = id;
8318
0
}
8319
8320
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8321
0
{
8322
0
    ImGuiContext& g = *GImGui;
8323
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8324
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8325
0
    g.NextWindowData.DockId = id;
8326
0
}
8327
8328
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8329
0
{
8330
0
    ImGuiContext& g = *GImGui;
8331
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8332
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8333
0
    g.NextWindowData.WindowClass = *window_class;
8334
0
}
8335
8336
ImDrawList* ImGui::GetWindowDrawList()
8337
23.6k
{
8338
23.6k
    ImGuiWindow* window = GetCurrentWindow();
8339
23.6k
    return window->DrawList;
8340
23.6k
}
8341
8342
float ImGui::GetWindowDpiScale()
8343
0
{
8344
0
    ImGuiContext& g = *GImGui;
8345
0
    return g.CurrentDpiScale;
8346
0
}
8347
8348
ImGuiViewport* ImGui::GetWindowViewport()
8349
0
{
8350
0
    ImGuiContext& g = *GImGui;
8351
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8352
0
    return g.CurrentViewport;
8353
0
}
8354
8355
ImFont* ImGui::GetFont()
8356
18.6M
{
8357
18.6M
    return GImGui->Font;
8358
18.6M
}
8359
8360
float ImGui::GetFontSize()
8361
18.6M
{
8362
18.6M
    return GImGui->FontSize;
8363
18.6M
}
8364
8365
ImVec2 ImGui::GetFontTexUvWhitePixel()
8366
0
{
8367
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8368
0
}
8369
8370
void ImGui::SetWindowFontScale(float scale)
8371
0
{
8372
0
    IM_ASSERT(scale > 0.0f);
8373
0
    ImGuiContext& g = *GImGui;
8374
0
    ImGuiWindow* window = GetCurrentWindow();
8375
0
    window->FontWindowScale = scale;
8376
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8377
0
}
8378
8379
void ImGui::PushFocusScope(ImGuiID id)
8380
71.8k
{
8381
71.8k
    ImGuiContext& g = *GImGui;
8382
71.8k
    g.FocusScopeStack.push_back(id);
8383
71.8k
    g.CurrentFocusScopeId = id;
8384
71.8k
}
8385
8386
void ImGui::PopFocusScope()
8387
71.8k
{
8388
71.8k
    ImGuiContext& g = *GImGui;
8389
71.8k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8390
71.8k
    g.FocusScopeStack.pop_back();
8391
71.8k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8392
71.8k
}
8393
8394
// Focus = move navigation cursor, set scrolling, set focus window.
8395
void ImGui::FocusItem()
8396
0
{
8397
0
    ImGuiContext& g = *GImGui;
8398
0
    ImGuiWindow* window = g.CurrentWindow;
8399
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8400
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8401
0
    {
8402
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8403
0
        return;
8404
0
    }
8405
8406
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8407
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8408
0
    SetNavWindow(window);
8409
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8410
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8411
0
}
8412
8413
void ImGui::ActivateItemByID(ImGuiID id)
8414
0
{
8415
0
    ImGuiContext& g = *GImGui;
8416
0
    g.NavNextActivateId = id;
8417
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8418
0
}
8419
8420
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8421
// But ActivateItem() should function without altering scroll/focus?
8422
void ImGui::SetKeyboardFocusHere(int offset)
8423
0
{
8424
0
    ImGuiContext& g = *GImGui;
8425
0
    ImGuiWindow* window = g.CurrentWindow;
8426
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8427
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8428
8429
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8430
    // When we refactor this function into ActivateItem() we may want to make this an option.
8431
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8432
    // is also automatically dropped in the event g.ActiveId is stolen.
8433
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8434
0
    {
8435
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8436
0
        return;
8437
0
    }
8438
8439
0
    SetNavWindow(window);
8440
8441
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8442
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8443
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8444
0
    if (offset == -1)
8445
0
    {
8446
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8447
0
    }
8448
0
    else
8449
0
    {
8450
0
        g.NavTabbingDir = 1;
8451
0
        g.NavTabbingCounter = offset + 1;
8452
0
    }
8453
0
}
8454
8455
void ImGui::SetItemDefaultFocus()
8456
0
{
8457
0
    ImGuiContext& g = *GImGui;
8458
0
    ImGuiWindow* window = g.CurrentWindow;
8459
0
    if (!window->Appearing)
8460
0
        return;
8461
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8462
0
        return;
8463
8464
0
    g.NavInitRequest = false;
8465
0
    NavApplyItemToResult(&g.NavInitResult);
8466
0
    NavUpdateAnyRequestFlag();
8467
8468
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8469
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8470
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8471
0
}
8472
8473
void ImGui::SetStateStorage(ImGuiStorage* tree)
8474
0
{
8475
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8476
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8477
0
}
8478
8479
ImGuiStorage* ImGui::GetStateStorage()
8480
0
{
8481
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8482
0
    return window->DC.StateStorage;
8483
0
}
8484
8485
void ImGui::PushID(const char* str_id)
8486
23.6k
{
8487
23.6k
    ImGuiContext& g = *GImGui;
8488
23.6k
    ImGuiWindow* window = g.CurrentWindow;
8489
23.6k
    ImGuiID id = window->GetID(str_id);
8490
23.6k
    window->IDStack.push_back(id);
8491
23.6k
}
8492
8493
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8494
0
{
8495
0
    ImGuiContext& g = *GImGui;
8496
0
    ImGuiWindow* window = g.CurrentWindow;
8497
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8498
0
    window->IDStack.push_back(id);
8499
0
}
8500
8501
void ImGui::PushID(const void* ptr_id)
8502
0
{
8503
0
    ImGuiContext& g = *GImGui;
8504
0
    ImGuiWindow* window = g.CurrentWindow;
8505
0
    ImGuiID id = window->GetID(ptr_id);
8506
0
    window->IDStack.push_back(id);
8507
0
}
8508
8509
void ImGui::PushID(int int_id)
8510
0
{
8511
0
    ImGuiContext& g = *GImGui;
8512
0
    ImGuiWindow* window = g.CurrentWindow;
8513
0
    ImGuiID id = window->GetID(int_id);
8514
0
    window->IDStack.push_back(id);
8515
0
}
8516
8517
// Push a given id value ignoring the ID stack as a seed.
8518
void ImGui::PushOverrideID(ImGuiID id)
8519
0
{
8520
0
    ImGuiContext& g = *GImGui;
8521
0
    ImGuiWindow* window = g.CurrentWindow;
8522
0
    if (g.DebugHookIdInfo == id)
8523
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8524
0
    window->IDStack.push_back(id);
8525
0
}
8526
8527
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8528
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8529
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8530
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8531
0
{
8532
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8533
0
    ImGuiContext& g = *GImGui;
8534
0
    if (g.DebugHookIdInfo == id)
8535
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8536
0
    return id;
8537
0
}
8538
8539
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8540
0
{
8541
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8542
0
    ImGuiContext& g = *GImGui;
8543
0
    if (g.DebugHookIdInfo == id)
8544
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8545
0
    return id;
8546
0
}
8547
8548
void ImGui::PopID()
8549
23.6k
{
8550
23.6k
    ImGuiWindow* window = GImGui->CurrentWindow;
8551
23.6k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8552
23.6k
    window->IDStack.pop_back();
8553
23.6k
}
8554
8555
ImGuiID ImGui::GetID(const char* str_id)
8556
0
{
8557
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8558
0
    return window->GetID(str_id);
8559
0
}
8560
8561
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8562
0
{
8563
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8564
0
    return window->GetID(str_id_begin, str_id_end);
8565
0
}
8566
8567
ImGuiID ImGui::GetID(const void* ptr_id)
8568
0
{
8569
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8570
0
    return window->GetID(ptr_id);
8571
0
}
8572
8573
bool ImGui::IsRectVisible(const ImVec2& size)
8574
0
{
8575
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8576
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8577
0
}
8578
8579
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8580
0
{
8581
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8582
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8583
0
}
8584
8585
8586
//-----------------------------------------------------------------------------
8587
// [SECTION] INPUTS
8588
//-----------------------------------------------------------------------------
8589
// - GetKeyData() [Internal]
8590
// - GetKeyIndex() [Internal]
8591
// - GetKeyName()
8592
// - GetKeyChordName() [Internal]
8593
// - CalcTypematicRepeatAmount() [Internal]
8594
// - GetTypematicRepeatRate() [Internal]
8595
// - GetKeyPressedAmount() [Internal]
8596
// - GetKeyMagnitude2d() [Internal]
8597
//-----------------------------------------------------------------------------
8598
// - UpdateKeyRoutingTable() [Internal]
8599
// - GetRoutingIdFromOwnerId() [Internal]
8600
// - GetShortcutRoutingData() [Internal]
8601
// - CalcRoutingScore() [Internal]
8602
// - SetShortcutRouting() [Internal]
8603
// - TestShortcutRouting() [Internal]
8604
//-----------------------------------------------------------------------------
8605
// - IsKeyDown()
8606
// - IsKeyPressed()
8607
// - IsKeyReleased()
8608
//-----------------------------------------------------------------------------
8609
// - IsMouseDown()
8610
// - IsMouseClicked()
8611
// - IsMouseReleased()
8612
// - IsMouseDoubleClicked()
8613
// - GetMouseClickedCount()
8614
// - IsMouseHoveringRect() [Internal]
8615
// - IsMouseDragPastThreshold() [Internal]
8616
// - IsMouseDragging()
8617
// - GetMousePos()
8618
// - SetMousePos() [Internal]
8619
// - GetMousePosOnOpeningCurrentPopup()
8620
// - IsMousePosValid()
8621
// - IsAnyMouseDown()
8622
// - GetMouseDragDelta()
8623
// - ResetMouseDragDelta()
8624
// - GetMouseCursor()
8625
// - SetMouseCursor()
8626
//-----------------------------------------------------------------------------
8627
// - UpdateAliasKey()
8628
// - GetMergedModsFromKeys()
8629
// - UpdateKeyboardInputs()
8630
// - UpdateMouseInputs()
8631
//-----------------------------------------------------------------------------
8632
// - LockWheelingWindow [Internal]
8633
// - FindBestWheelingWindow [Internal]
8634
// - UpdateMouseWheel() [Internal]
8635
//-----------------------------------------------------------------------------
8636
// - SetNextFrameWantCaptureKeyboard()
8637
// - SetNextFrameWantCaptureMouse()
8638
//-----------------------------------------------------------------------------
8639
// - GetInputSourceName() [Internal]
8640
// - DebugPrintInputEvent() [Internal]
8641
// - UpdateInputEvents() [Internal]
8642
//-----------------------------------------------------------------------------
8643
// - GetKeyOwner() [Internal]
8644
// - TestKeyOwner() [Internal]
8645
// - SetKeyOwner() [Internal]
8646
// - SetItemKeyOwner() [Internal]
8647
// - Shortcut() [Internal]
8648
//-----------------------------------------------------------------------------
8649
8650
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8651
916k
{
8652
916k
    ImGuiContext& g = *ctx;
8653
8654
    // Special storage location for mods
8655
916k
    if (key & ImGuiMod_Mask_)
8656
216k
        key = ConvertSingleModFlagToKey(ctx, key);
8657
8658
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8659
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8660
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8661
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8662
#else
8663
916k
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8664
916k
#endif
8665
916k
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8666
916k
}
8667
8668
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8669
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8670
{
8671
    ImGuiContext& g = *GImGui;
8672
    IM_ASSERT(IsNamedKey(key));
8673
    const ImGuiKeyData* key_data = GetKeyData(key);
8674
    return (ImGuiKey)(key_data - g.IO.KeysData);
8675
}
8676
#endif
8677
8678
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8679
static const char* const GKeyNames[] =
8680
{
8681
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8682
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8683
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8684
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8685
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8686
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8687
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8688
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8689
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8690
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8691
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8692
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8693
    "AppBack", "AppForward",
8694
    "GamepadStart", "GamepadBack",
8695
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8696
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8697
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8698
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8699
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8700
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8701
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8702
};
8703
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8704
8705
const char* ImGui::GetKeyName(ImGuiKey key)
8706
0
{
8707
0
    ImGuiContext& g = *GImGui;
8708
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8709
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8710
#else
8711
    if (IsLegacyKey(key))
8712
    {
8713
        if (g.IO.KeyMap[key] == -1)
8714
            return "N/A";
8715
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8716
        key = (ImGuiKey)g.IO.KeyMap[key];
8717
    }
8718
#endif
8719
0
    if (key == ImGuiKey_None)
8720
0
        return "None";
8721
0
    if (key & ImGuiMod_Mask_)
8722
0
        key = ConvertSingleModFlagToKey(&g, key);
8723
0
    if (!IsNamedKey(key))
8724
0
        return "Unknown";
8725
8726
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8727
0
}
8728
8729
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8730
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8731
0
{
8732
0
    ImGuiContext& g = *GImGui;
8733
0
    if (key_chord & ImGuiMod_Shortcut)
8734
0
        key_chord = ConvertShortcutMod(key_chord);
8735
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8736
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8737
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8738
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8739
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8740
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8741
0
}
8742
8743
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8744
// t1 = current time (e.g.: g.Time)
8745
// An event is triggered at:
8746
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8747
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8748
5.88k
{
8749
5.88k
    if (t1 == 0.0f)
8750
0
        return 1;
8751
5.88k
    if (t0 >= t1)
8752
0
        return 0;
8753
5.88k
    if (repeat_rate <= 0.0f)
8754
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8755
5.88k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8756
5.88k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8757
5.88k
    const int count = count_t1 - count_t0;
8758
5.88k
    return count;
8759
5.88k
}
8760
8761
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8762
11.7k
{
8763
11.7k
    ImGuiContext& g = *GImGui;
8764
11.7k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8765
11.7k
    {
8766
4.38k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8767
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8768
7.37k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8769
11.7k
    }
8770
11.7k
}
8771
8772
// Return value representing the number of presses in the last time period, for the given repeat rate
8773
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8774
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8775
5.88k
{
8776
5.88k
    ImGuiContext& g = *GImGui;
8777
5.88k
    const ImGuiKeyData* key_data = GetKeyData(key);
8778
5.88k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8779
0
        return 0;
8780
5.88k
    const float t = key_data->DownDuration;
8781
5.88k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8782
5.88k
}
8783
8784
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8785
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8786
0
{
8787
0
    return ImVec2(
8788
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8789
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8790
0
}
8791
8792
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8793
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8794
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8795
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8796
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8797
24.1k
{
8798
24.1k
    ImGuiContext& g = *GImGui;
8799
24.1k
    rt->EntriesNext.resize(0);
8800
3.73M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8801
3.71M
    {
8802
3.71M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8803
3.71M
        ImGuiKeyRoutingData* routing_entry;
8804
3.71M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8805
0
        {
8806
0
            routing_entry = &rt->Entries[old_routing_idx];
8807
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8808
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8809
0
            routing_entry->RoutingNextScore = 255;
8810
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8811
0
                continue;
8812
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8813
8814
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8815
0
            if (routing_entry->Mods == g.IO.KeyMods)
8816
0
            {
8817
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8818
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8819
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8820
0
            }
8821
0
        }
8822
8823
        // Rewrite linked-list
8824
3.71M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8825
3.71M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8826
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8827
3.71M
    }
8828
24.1k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8829
24.1k
}
8830
8831
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8832
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8833
0
{
8834
0
    ImGuiContext& g = *GImGui;
8835
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8836
0
}
8837
8838
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8839
0
{
8840
    // Majority of shortcuts will be Key + any number of Mods
8841
    // We accept _Single_ mod with ImGuiKey_None.
8842
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8843
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8844
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8845
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8846
0
    ImGuiContext& g = *GImGui;
8847
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8848
0
    ImGuiKeyRoutingData* routing_data;
8849
0
    if (key_chord & ImGuiMod_Shortcut)
8850
0
        key_chord = ConvertShortcutMod(key_chord);
8851
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8852
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8853
0
    if (key == ImGuiKey_None)
8854
0
        key = ConvertSingleModFlagToKey(&g, mods);
8855
0
    IM_ASSERT(IsNamedKey(key));
8856
8857
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8858
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8859
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8860
0
    {
8861
0
        routing_data = &rt->Entries[idx];
8862
0
        if (routing_data->Mods == mods)
8863
0
            return routing_data;
8864
0
    }
8865
8866
    // Add to linked-list
8867
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8868
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8869
0
    routing_data = &rt->Entries[routing_data_idx];
8870
0
    routing_data->Mods = (ImU16)mods;
8871
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8872
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8873
0
    return routing_data;
8874
0
}
8875
8876
// Current score encoding (lower is highest priority):
8877
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8878
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8879
//  -   2: ImGuiInputFlags_RouteGlobal
8880
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8881
//  - 254: ImGuiInputFlags_RouteGlobalLow
8882
//  - 255: never route
8883
// 'flags' should include an explicit routing policy
8884
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8885
0
{
8886
0
    if (flags & ImGuiInputFlags_RouteFocused)
8887
0
    {
8888
0
        ImGuiContext& g = *GImGui;
8889
0
        ImGuiWindow* focused = g.NavWindow;
8890
8891
        // ActiveID gets top priority
8892
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8893
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8894
0
            return 1;
8895
8896
        // Score based on distance to focused window (lower is better)
8897
        // Assuming both windows are submitting a routing request,
8898
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8899
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8900
        // Assuming only WindowA is submitting a routing request,
8901
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8902
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8903
0
            for (int next_score = 3; focused != NULL; next_score++)
8904
0
            {
8905
0
                if (focused == location)
8906
0
                {
8907
0
                    IM_ASSERT(next_score < 255);
8908
0
                    return next_score;
8909
0
                }
8910
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8911
0
            }
8912
0
        return 255;
8913
0
    }
8914
8915
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8916
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8917
0
        return 2;
8918
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8919
0
        return 254;
8920
0
    return 0;
8921
0
}
8922
8923
// Request a desired route for an input chord (key + mods).
8924
// Return true if the route is available this frame.
8925
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8926
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8927
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8928
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8929
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8930
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8931
48.2k
{
8932
48.2k
    ImGuiContext& g = *GImGui;
8933
48.2k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8934
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8935
48.2k
    else
8936
48.2k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8937
8938
48.2k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8939
0
        if (g.NavWindow == NULL)
8940
0
            return false;
8941
48.2k
    if (flags & ImGuiInputFlags_RouteAlways)
8942
48.2k
        return true;
8943
8944
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8945
0
    if (score == 255)
8946
0
        return false;
8947
8948
    // Submit routing for NEXT frame (assuming score is sufficient)
8949
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8950
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8951
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8952
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8953
0
    if (score < routing_data->RoutingNextScore)
8954
0
    {
8955
0
        routing_data->RoutingNext = routing_id;
8956
0
        routing_data->RoutingNextScore = (ImU8)score;
8957
0
    }
8958
8959
    // Return routing state for CURRENT frame
8960
0
    return routing_data->RoutingCurr == routing_id;
8961
0
}
8962
8963
// Currently unused by core (but used by tests)
8964
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8965
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8966
0
{
8967
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8968
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8969
0
    return routing_data->RoutingCurr == routing_id;
8970
0
}
8971
8972
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8973
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8974
bool ImGui::IsKeyDown(ImGuiKey key)
8975
369k
{
8976
369k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8977
369k
}
8978
8979
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8980
401k
{
8981
401k
    const ImGuiKeyData* key_data = GetKeyData(key);
8982
401k
    if (!key_data->Down)
8983
388k
        return false;
8984
12.3k
    if (!TestKeyOwner(key, owner_id))
8985
22
        return false;
8986
12.3k
    return true;
8987
12.3k
}
8988
8989
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8990
175k
{
8991
175k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8992
175k
}
8993
8994
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8995
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8996
337k
{
8997
337k
    const ImGuiKeyData* key_data = GetKeyData(key);
8998
337k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8999
320k
        return false;
9000
16.8k
    const float t = key_data->DownDuration;
9001
16.8k
    if (t < 0.0f)
9002
0
        return false;
9003
16.8k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9004
9005
16.8k
    bool pressed = (t == 0.0f);
9006
16.8k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
9007
11.7k
    {
9008
11.7k
        float repeat_delay, repeat_rate;
9009
11.7k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9010
11.7k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9011
11.7k
    }
9012
16.8k
    if (!pressed)
9013
13.9k
        return false;
9014
2.97k
    if (!TestKeyOwner(key, owner_id))
9015
0
        return false;
9016
2.97k
    return true;
9017
2.97k
}
9018
9019
bool ImGui::IsKeyReleased(ImGuiKey key)
9020
0
{
9021
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9022
0
}
9023
9024
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9025
0
{
9026
0
    const ImGuiKeyData* key_data = GetKeyData(key);
9027
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9028
0
        return false;
9029
0
    if (!TestKeyOwner(key, owner_id))
9030
0
        return false;
9031
0
    return true;
9032
0
}
9033
9034
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9035
0
{
9036
0
    ImGuiContext& g = *GImGui;
9037
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9038
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9039
0
}
9040
9041
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9042
0
{
9043
0
    ImGuiContext& g = *GImGui;
9044
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9045
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9046
0
}
9047
9048
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9049
529
{
9050
529
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9051
529
}
9052
9053
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9054
620
{
9055
620
    ImGuiContext& g = *GImGui;
9056
620
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9057
620
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9058
198
        return false;
9059
422
    const float t = g.IO.MouseDownDuration[button];
9060
422
    if (t < 0.0f)
9061
0
        return false;
9062
422
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9063
9064
422
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9065
422
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9066
422
    if (!pressed)
9067
396
        return false;
9068
9069
26
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9070
0
        return false;
9071
9072
26
    return true;
9073
26
}
9074
9075
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9076
0
{
9077
0
    ImGuiContext& g = *GImGui;
9078
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9079
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9080
0
}
9081
9082
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9083
91
{
9084
91
    ImGuiContext& g = *GImGui;
9085
91
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9086
91
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9087
91
}
9088
9089
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9090
529
{
9091
529
    ImGuiContext& g = *GImGui;
9092
529
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9093
529
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9094
529
}
9095
9096
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9097
0
{
9098
0
    ImGuiContext& g = *GImGui;
9099
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9100
0
    return g.IO.MouseClickedCount[button];
9101
0
}
9102
9103
// Test if mouse cursor is hovering given rectangle
9104
// NB- Rectangle is clipped by our current clip setting
9105
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9106
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9107
177k
{
9108
177k
    ImGuiContext& g = *GImGui;
9109
9110
    // Clip
9111
177k
    ImRect rect_clipped(r_min, r_max);
9112
177k
    if (clip)
9113
105k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9114
9115
    // Hit testing, expanded for touch input
9116
177k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9117
175k
        return false;
9118
2.50k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9119
0
        return false;
9120
2.50k
    return true;
9121
2.50k
}
9122
9123
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9124
// [Internal] This doesn't test if the button is pressed
9125
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9126
528
{
9127
528
    ImGuiContext& g = *GImGui;
9128
528
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9129
528
    if (lock_threshold < 0.0f)
9130
528
        lock_threshold = g.IO.MouseDragThreshold;
9131
528
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9132
528
}
9133
9134
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9135
635
{
9136
635
    ImGuiContext& g = *GImGui;
9137
635
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9138
635
    if (!g.IO.MouseDown[button])
9139
107
        return false;
9140
528
    return IsMouseDragPastThreshold(button, lock_threshold);
9141
635
}
9142
9143
ImVec2 ImGui::GetMousePos()
9144
5.42k
{
9145
5.42k
    ImGuiContext& g = *GImGui;
9146
5.42k
    return g.IO.MousePos;
9147
5.42k
}
9148
9149
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9150
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9151
void ImGui::TeleportMousePos(const ImVec2& pos)
9152
0
{
9153
0
    ImGuiContext& g = *GImGui;
9154
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9155
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9156
0
    g.IO.WantSetMousePos = true;
9157
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9158
0
}
9159
9160
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9161
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9162
0
{
9163
0
    ImGuiContext& g = *GImGui;
9164
0
    if (g.BeginPopupStack.Size > 0)
9165
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9166
0
    return g.IO.MousePos;
9167
0
}
9168
9169
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9170
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9171
82.4k
{
9172
    // The assert is only to silence a false-positive in XCode Static Analysis.
9173
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9174
82.4k
    IM_ASSERT(GImGui != NULL);
9175
82.4k
    const float MOUSE_INVALID = -256000.0f;
9176
82.4k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9177
82.4k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9178
82.4k
}
9179
9180
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9181
bool ImGui::IsAnyMouseDown()
9182
0
{
9183
0
    ImGuiContext& g = *GImGui;
9184
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9185
0
        if (g.IO.MouseDown[n])
9186
0
            return true;
9187
0
    return false;
9188
0
}
9189
9190
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9191
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9192
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9193
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9194
0
{
9195
0
    ImGuiContext& g = *GImGui;
9196
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9197
0
    if (lock_threshold < 0.0f)
9198
0
        lock_threshold = g.IO.MouseDragThreshold;
9199
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9200
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9201
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9202
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9203
0
    return ImVec2(0.0f, 0.0f);
9204
0
}
9205
9206
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9207
0
{
9208
0
    ImGuiContext& g = *GImGui;
9209
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9210
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9211
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9212
0
}
9213
9214
// Get desired mouse cursor shape.
9215
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9216
// updated during the frame, and locked in EndFrame()/Render().
9217
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9218
ImGuiMouseCursor ImGui::GetMouseCursor()
9219
0
{
9220
0
    ImGuiContext& g = *GImGui;
9221
0
    return g.MouseCursor;
9222
0
}
9223
9224
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9225
445
{
9226
445
    ImGuiContext& g = *GImGui;
9227
445
    g.MouseCursor = cursor_type;
9228
445
}
9229
9230
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9231
168k
{
9232
168k
    IM_ASSERT(ImGui::IsAliasKey(key));
9233
168k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9234
168k
    key_data->Down = v;
9235
168k
    key_data->AnalogValue = analog_value;
9236
168k
}
9237
9238
// [Internal] Do not use directly
9239
static ImGuiKeyChord GetMergedModsFromKeys()
9240
48.2k
{
9241
48.2k
    ImGuiKeyChord mods = 0;
9242
48.2k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9243
48.2k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9244
48.2k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9245
48.2k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9246
48.2k
    return mods;
9247
48.2k
}
9248
9249
static void ImGui::UpdateKeyboardInputs()
9250
24.1k
{
9251
24.1k
    ImGuiContext& g = *GImGui;
9252
24.1k
    ImGuiIO& io = g.IO;
9253
9254
    // Import legacy keys or verify they are not used
9255
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9256
    if (io.BackendUsingLegacyKeyArrays == 0)
9257
    {
9258
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9259
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9260
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9261
    }
9262
    else
9263
    {
9264
        if (g.FrameCount == 0)
9265
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9266
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9267
9268
        // Build reverse KeyMap (Named -> Legacy)
9269
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9270
            if (io.KeyMap[n] != -1)
9271
            {
9272
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9273
                io.KeyMap[io.KeyMap[n]] = n;
9274
            }
9275
9276
        // Import legacy keys into new ones
9277
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9278
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9279
            {
9280
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9281
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9282
                io.KeysData[key].Down = io.KeysDown[n];
9283
                if (key != n)
9284
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9285
                io.BackendUsingLegacyKeyArrays = 1;
9286
            }
9287
        if (io.BackendUsingLegacyKeyArrays == 1)
9288
        {
9289
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9290
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9291
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9292
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9293
        }
9294
    }
9295
9296
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9297
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9298
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9299
    {
9300
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9301
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9302
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9303
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9304
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9305
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9306
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9307
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9308
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9309
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9310
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9311
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9312
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9313
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9314
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9315
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9316
        #undef NAV_MAP_KEY
9317
    }
9318
#endif
9319
#endif
9320
9321
    // Update aliases
9322
144k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9323
120k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9324
24.1k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9325
24.1k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9326
9327
    // Synchronize io.KeyMods and io.KeyXXX values.
9328
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9329
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9330
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9331
24.1k
    io.KeyMods = GetMergedModsFromKeys();
9332
24.1k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9333
24.1k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9334
24.1k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9335
24.1k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9336
9337
    // Clear gamepad data if disabled
9338
24.1k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9339
602k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9340
578k
        {
9341
578k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9342
578k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9343
578k
        }
9344
9345
    // Update keys
9346
3.73M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9347
3.71M
    {
9348
3.71M
        ImGuiKeyData* key_data = &io.KeysData[i];
9349
3.71M
        key_data->DownDurationPrev = key_data->DownDuration;
9350
3.71M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9351
3.71M
    }
9352
9353
    // Update keys/input owner (named keys only): one entry per key
9354
3.73M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9355
3.71M
    {
9356
3.71M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9357
3.71M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9358
3.71M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9359
3.71M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9360
3.69M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9361
3.71M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9362
3.71M
    }
9363
9364
24.1k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9365
24.1k
}
9366
9367
static void ImGui::UpdateMouseInputs()
9368
24.1k
{
9369
24.1k
    ImGuiContext& g = *GImGui;
9370
24.1k
    ImGuiIO& io = g.IO;
9371
9372
    // Mouse Wheel swapping flag
9373
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9374
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9375
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9376
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9377
24.1k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9378
9379
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9380
24.1k
    if (IsMousePosValid(&io.MousePos))
9381
5.49k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9382
9383
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9384
24.1k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9385
4.98k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9386
19.1k
    else
9387
19.1k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9388
9389
    // Update stationary timer.
9390
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9391
24.1k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9392
24.1k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9393
24.1k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9394
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9395
9396
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9397
24.1k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9398
291
        g.NavDisableMouseHover = false;
9399
9400
144k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9401
120k
    {
9402
120k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9403
120k
        io.MouseClickedCount[i] = 0; // Will be filled below
9404
120k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9405
120k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9406
120k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9407
120k
        if (io.MouseClicked[i])
9408
725
        {
9409
725
            bool is_repeated_click = false;
9410
725
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9411
363
            {
9412
363
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9413
363
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9414
319
                    is_repeated_click = true;
9415
363
            }
9416
725
            if (is_repeated_click)
9417
319
                io.MouseClickedLastCount[i]++;
9418
406
            else
9419
406
                io.MouseClickedLastCount[i] = 1;
9420
725
            io.MouseClickedTime[i] = g.Time;
9421
725
            io.MouseClickedPos[i] = io.MousePos;
9422
725
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9423
725
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9424
725
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9425
725
        }
9426
119k
        else if (io.MouseDown[i])
9427
4.62k
        {
9428
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9429
4.62k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9430
4.62k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9431
4.62k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9432
4.62k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9433
4.62k
        }
9434
9435
        // We provide io.MouseDoubleClicked[] as a legacy service
9436
120k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9437
9438
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9439
120k
        if (io.MouseClicked[i])
9440
725
            g.NavDisableMouseHover = false;
9441
120k
    }
9442
24.1k
}
9443
9444
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9445
2
{
9446
2
    ImGuiContext& g = *GImGui;
9447
2
    if (window)
9448
1
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9449
1
    else
9450
1
        g.WheelingWindowReleaseTimer = 0.0f;
9451
2
    if (g.WheelingWindow == window)
9452
0
        return;
9453
2
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9454
2
    g.WheelingWindow = window;
9455
2
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9456
2
    if (window == NULL)
9457
1
    {
9458
1
        g.WheelingWindowStartFrame = -1;
9459
1
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9460
1
    }
9461
2
}
9462
9463
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9464
27
{
9465
    // For each axis, find window in the hierarchy that may want to use scrolling
9466
27
    ImGuiContext& g = *GImGui;
9467
27
    ImGuiWindow* windows[2] = { NULL, NULL };
9468
81
    for (int axis = 0; axis < 2; axis++)
9469
54
        if (wheel[axis] != 0.0f)
9470
67
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9471
27
            {
9472
                // Bubble up into parent window if:
9473
                // - a child window doesn't allow any scrolling.
9474
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9475
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9476
27
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9477
27
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9478
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9479
27
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9480
0
                    break; // select this window
9481
27
            }
9482
27
    if (windows[0] == NULL && windows[1] == NULL)
9483
0
        return NULL;
9484
9485
    // If there's only one window or only one axis then there's no ambiguity
9486
27
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9487
27
        return windows[1] ? windows[1] : windows[0];
9488
9489
    // If candidate are different windows we need to decide which one to prioritize
9490
    // - First frame: only find a winner if one axis is zero.
9491
    // - Subsequent frames: only find a winner when one is more than the other.
9492
0
    if (g.WheelingWindowStartFrame == -1)
9493
0
        g.WheelingWindowStartFrame = g.FrameCount;
9494
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9495
0
    {
9496
0
        g.WheelingWindowWheelRemainder = wheel;
9497
0
        return NULL;
9498
0
    }
9499
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9500
0
}
9501
9502
// Called by NewFrame()
9503
void ImGui::UpdateMouseWheel()
9504
24.1k
{
9505
    // Reset the locked window if we move the mouse or after the timer elapses.
9506
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9507
24.1k
    ImGuiContext& g = *GImGui;
9508
24.1k
    if (g.WheelingWindow != NULL)
9509
1
    {
9510
1
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9511
1
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9512
1
            g.WheelingWindowReleaseTimer = 0.0f;
9513
1
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9514
1
            LockWheelingWindow(NULL, 0.0f);
9515
1
    }
9516
9517
24.1k
    ImVec2 wheel;
9518
24.1k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9519
24.1k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9520
9521
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9522
24.1k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9523
24.1k
    if (!mouse_window || mouse_window->Collapsed)
9524
23.1k
        return;
9525
9526
    // Zoom / Scale window
9527
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9528
952
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9529
0
    {
9530
0
        LockWheelingWindow(mouse_window, wheel.y);
9531
0
        ImGuiWindow* window = mouse_window;
9532
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9533
0
        const float scale = new_font_scale / window->FontWindowScale;
9534
0
        window->FontWindowScale = new_font_scale;
9535
0
        if (window == window->RootWindow)
9536
0
        {
9537
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9538
0
            SetWindowPos(window, window->Pos + offset, 0);
9539
0
            window->Size = ImTrunc(window->Size * scale);
9540
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
9541
0
        }
9542
0
        return;
9543
0
    }
9544
952
    if (g.IO.KeyCtrl)
9545
0
        return;
9546
9547
    // Mouse wheel scrolling
9548
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9549
952
    if (g.IO.MouseWheelRequestAxisSwap)
9550
0
        wheel = ImVec2(wheel.y, 0.0f);
9551
9552
    // Maintain a rough average of moving magnitude on both axises
9553
    // FIXME: should by based on wall clock time rather than frame-counter
9554
952
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9555
952
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9556
9557
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9558
952
    wheel += g.WheelingWindowWheelRemainder;
9559
952
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9560
952
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9561
925
        return;
9562
9563
    // Mouse wheel scrolling: find target and apply
9564
    // - don't renew lock if axis doesn't apply on the window.
9565
    // - select a main axis when both axises are being moved.
9566
27
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9567
27
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9568
27
        {
9569
27
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9570
27
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9571
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9572
27
            if (do_scroll[ImGuiAxis_X])
9573
0
            {
9574
0
                LockWheelingWindow(window, wheel.x);
9575
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9576
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9577
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9578
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9579
0
            }
9580
27
            if (do_scroll[ImGuiAxis_Y])
9581
1
            {
9582
1
                LockWheelingWindow(window, wheel.y);
9583
1
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9584
1
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9585
1
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9586
1
                g.WheelingWindowScrolledFrame = g.FrameCount;
9587
1
            }
9588
27
        }
9589
27
}
9590
9591
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9592
0
{
9593
0
    ImGuiContext& g = *GImGui;
9594
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9595
0
}
9596
9597
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9598
0
{
9599
0
    ImGuiContext& g = *GImGui;
9600
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9601
0
}
9602
9603
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9604
static const char* GetInputSourceName(ImGuiInputSource source)
9605
0
{
9606
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9607
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9608
0
    return input_source_names[source];
9609
0
}
9610
static const char* GetMouseSourceName(ImGuiMouseSource source)
9611
0
{
9612
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9613
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9614
0
    return mouse_source_names[source];
9615
0
}
9616
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9617
0
{
9618
0
    ImGuiContext& g = *GImGui;
9619
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9620
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9621
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9622
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9623
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9624
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9625
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9626
0
}
9627
#endif
9628
9629
// Process input queue
9630
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9631
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9632
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9633
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9634
24.1k
{
9635
24.1k
    ImGuiContext& g = *GImGui;
9636
24.1k
    ImGuiIO& io = g.IO;
9637
9638
    // Only trickle chars<>key when working with InputText()
9639
    // FIXME: InputText() could parse event trail?
9640
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9641
24.1k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9642
9643
24.1k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9644
24.1k
    int  mouse_button_changed = 0x00;
9645
24.1k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9646
9647
24.1k
    int event_n = 0;
9648
30.5k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9649
7.42k
    {
9650
7.42k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9651
7.42k
        if (e->Type == ImGuiInputEventType_MousePos)
9652
1.25k
        {
9653
1.25k
            if (g.IO.WantSetMousePos)
9654
0
                continue;
9655
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9656
1.25k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9657
1.25k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9658
105
                break;
9659
1.15k
            io.MousePos = event_pos;
9660
1.15k
            io.MouseSource = e->MousePos.MouseSource;
9661
1.15k
            mouse_moved = true;
9662
1.15k
        }
9663
6.16k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9664
1.29k
        {
9665
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9666
1.29k
            const ImGuiMouseButton button = e->MouseButton.Button;
9667
1.29k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9668
1.29k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9669
307
                break;
9670
989
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9671
0
                break;
9672
989
            io.MouseDown[button] = e->MouseButton.Down;
9673
989
            io.MouseSource = e->MouseButton.MouseSource;
9674
989
            mouse_button_changed |= (1 << button);
9675
989
        }
9676
4.86k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9677
608
        {
9678
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9679
608
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9680
107
                break;
9681
501
            io.MouseWheelH += e->MouseWheel.WheelX;
9682
501
            io.MouseWheel += e->MouseWheel.WheelY;
9683
501
            io.MouseSource = e->MouseWheel.MouseSource;
9684
501
            mouse_wheeled = true;
9685
501
        }
9686
4.26k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9687
0
        {
9688
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9689
0
        }
9690
4.26k
        else if (e->Type == ImGuiInputEventType_Key)
9691
1.25k
        {
9692
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9693
1.25k
            ImGuiKey key = e->Key.Key;
9694
1.25k
            IM_ASSERT(key != ImGuiKey_None);
9695
1.25k
            ImGuiKeyData* key_data = GetKeyData(key);
9696
1.25k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9697
1.25k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9698
201
                break;
9699
1.05k
            key_data->Down = e->Key.Down;
9700
1.05k
            key_data->AnalogValue = e->Key.AnalogValue;
9701
1.05k
            key_changed = true;
9702
1.05k
            key_changed_mask.SetBit(key_data_index);
9703
9704
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9705
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9706
            io.KeysDown[key_data_index] = key_data->Down;
9707
            if (io.KeyMap[key_data_index] != -1)
9708
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9709
#endif
9710
1.05k
        }
9711
3.00k
        else if (e->Type == ImGuiInputEventType_Text)
9712
2.79k
        {
9713
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9714
2.79k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9715
219
                break;
9716
2.57k
            unsigned int c = e->Text.Char;
9717
2.57k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9718
2.57k
            if (trickle_interleaved_keys_and_text)
9719
0
                text_inputted = true;
9720
2.57k
        }
9721
214
        else if (e->Type == ImGuiInputEventType_Focus)
9722
214
        {
9723
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9724
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9725
214
            const bool focus_lost = !e->AppFocused.Focused;
9726
214
            io.AppFocusLost = focus_lost;
9727
214
        }
9728
0
        else
9729
0
        {
9730
0
            IM_ASSERT(0 && "Unknown event!");
9731
0
        }
9732
7.42k
    }
9733
9734
    // Record trail (for domain-specific applications wanting to access a precise trail)
9735
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9736
30.5k
    for (int n = 0; n < event_n; n++)
9737
6.48k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9738
9739
    // [DEBUG]
9740
24.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9741
24.1k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9742
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9743
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9744
24.1k
#endif
9745
9746
    // Remaining events will be processed on the next frame
9747
24.1k
    if (event_n == g.InputEventsQueue.Size)
9748
23.1k
        g.InputEventsQueue.resize(0);
9749
939
    else
9750
939
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9751
9752
    // Clear buttons state when focus is lost
9753
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9754
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9755
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9756
24.1k
    if (g.IO.AppFocusLost)
9757
146
        g.IO.ClearInputKeys();
9758
24.1k
}
9759
9760
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9761
0
{
9762
0
    if (!IsNamedKeyOrModKey(key))
9763
0
        return ImGuiKeyOwner_None;
9764
9765
0
    ImGuiContext& g = *GImGui;
9766
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9767
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9768
9769
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9770
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9771
0
            return ImGuiKeyOwner_None;
9772
9773
0
    return owner_id;
9774
0
}
9775
9776
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9777
// TestKeyOwner(..., None) : (owner == None)
9778
// TestKeyOwner(..., Any)  : no owner test
9779
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9780
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9781
63.6k
{
9782
63.6k
    if (!IsNamedKeyOrModKey(key))
9783
0
        return true;
9784
9785
63.6k
    ImGuiContext& g = *GImGui;
9786
63.6k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9787
1.33k
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9788
22
            return false;
9789
9790
63.5k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9791
63.5k
    if (owner_id == ImGuiKeyOwner_Any)
9792
12.3k
        return (owner_data->LockThisFrame == false);
9793
9794
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9795
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9796
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9797
51.2k
    if (owner_data->OwnerCurr != owner_id)
9798
0
    {
9799
0
        if (owner_data->LockThisFrame)
9800
0
            return false;
9801
0
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9802
0
            return false;
9803
0
    }
9804
9805
51.2k
    return true;
9806
51.2k
}
9807
9808
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9809
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9810
// - SetKeyOwner(..., None)              : clears owner
9811
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9812
// - SetKeyOwner(..., Any or None, Lock) : set lock
9813
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9814
0
{
9815
0
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9816
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9817
9818
0
    ImGuiContext& g = *GImGui;
9819
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9820
0
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9821
9822
    // We cannot lock by default as it would likely break lots of legacy code.
9823
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9824
0
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9825
0
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9826
0
}
9827
9828
// Rarely used helper
9829
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9830
0
{
9831
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9832
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9833
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9834
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9835
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9836
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9837
0
}
9838
9839
// This is more or less equivalent to:
9840
//   if (IsItemHovered() || IsItemActive())
9841
//       SetKeyOwner(key, GetItemID());
9842
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9843
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9844
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9845
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9846
0
{
9847
0
    ImGuiContext& g = *GImGui;
9848
0
    ImGuiID id = g.LastItemData.ID;
9849
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9850
0
        return;
9851
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9852
0
        flags |= ImGuiInputFlags_CondDefault_;
9853
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9854
0
    {
9855
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9856
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9857
0
    }
9858
0
}
9859
9860
// This is the only public API until we expose owner_id versions of the API as replacements.
9861
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
9862
0
{
9863
0
    return IsKeyChordPressed(key_chord, 0, ImGuiInputFlags_None);
9864
0
}
9865
9866
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
9867
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9868
48.2k
{
9869
48.2k
    ImGuiContext& g = *GImGui;
9870
48.2k
    if (key_chord & ImGuiMod_Shortcut)
9871
0
        key_chord = ConvertShortcutMod(key_chord);
9872
48.2k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9873
48.2k
    if (g.IO.KeyMods != mods)
9874
48.2k
        return false;
9875
9876
    // Special storage location for mods
9877
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9878
0
    if (key == ImGuiKey_None)
9879
0
        key = ConvertSingleModFlagToKey(&g, mods);
9880
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9881
0
        return false;
9882
0
    return true;
9883
0
}
9884
9885
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9886
48.2k
{
9887
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9888
48.2k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9889
48.2k
        flags |= ImGuiInputFlags_RouteFocused;
9890
48.2k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9891
0
        return false;
9892
9893
48.2k
    if (!IsKeyChordPressed(key_chord, owner_id, flags))
9894
48.2k
        return false;
9895
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9896
0
    return true;
9897
48.2k
}
9898
9899
9900
//-----------------------------------------------------------------------------
9901
// [SECTION] ERROR CHECKING
9902
//-----------------------------------------------------------------------------
9903
9904
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9905
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9906
// If this triggers you have an issue:
9907
// - Most commonly: mismatched headers and compiled code version.
9908
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9909
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9910
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9911
//   Otherwise it is possible that different compilation units would see different structure layout
9912
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9913
1
{
9914
1
    bool error = false;
9915
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9916
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9917
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9918
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9919
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9920
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9921
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9922
1
    return !error;
9923
1
}
9924
9925
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9926
// This is causing issues and ambiguity and we need to retire that.
9927
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9928
// [Scenario 1]
9929
//  Previously this would make the window content size ~200x200:
9930
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9931
//  Instead, please submit an item:
9932
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9933
//  Alternative:
9934
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9935
// [Scenario 2]
9936
//  For reference this is one of the issue what we aim to fix with this change:
9937
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9938
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9939
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9940
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9941
0
{
9942
0
    ImGuiContext& g = *GImGui;
9943
0
    ImGuiWindow* window = g.CurrentWindow;
9944
0
    IM_ASSERT(window->DC.IsSetPos);
9945
0
    window->DC.IsSetPos = false;
9946
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9947
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9948
0
        return;
9949
0
    if (window->SkipItems)
9950
0
        return;
9951
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9952
#else
9953
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9954
#endif
9955
0
}
9956
9957
static void ImGui::ErrorCheckNewFrameSanityChecks()
9958
24.1k
{
9959
24.1k
    ImGuiContext& g = *GImGui;
9960
9961
    // Check user IM_ASSERT macro
9962
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9963
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9964
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9965
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9966
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9967
24.1k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9968
9969
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9970
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9971
#ifdef __EMSCRIPTEN__
9972
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9973
        g.IO.DeltaTime = 0.00001f;
9974
#endif
9975
9976
    // Check user data
9977
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9978
24.1k
    IM_ASSERT(g.Initialized);
9979
24.1k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9980
24.1k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9981
24.1k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9982
24.1k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9983
24.1k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9984
24.1k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9985
24.1k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9986
24.1k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9987
24.1k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9988
24.1k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9989
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9990
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9991
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9992
9993
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9994
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9995
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9996
#endif
9997
9998
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9999
24.1k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10000
1
        g.IO.ConfigWindowsResizeFromEdges = false;
10001
10002
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10003
24.1k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10004
24.1k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10005
24.1k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10006
24.1k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10007
10008
    // Perform simple checks: multi-viewport and platform windows support
10009
24.1k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10010
1
    {
10011
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10012
0
        {
10013
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10014
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10015
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10016
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10017
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10018
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10019
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10020
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10021
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10022
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10023
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10024
0
        }
10025
1
        else
10026
1
        {
10027
            // Disable feature, our backends do not support it
10028
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10029
1
        }
10030
10031
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10032
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10033
0
        {
10034
0
            IM_UNUSED(mon);
10035
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10036
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10037
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10038
0
        }
10039
1
    }
10040
24.1k
}
10041
10042
static void ImGui::ErrorCheckEndFrameSanityChecks()
10043
24.1k
{
10044
24.1k
    ImGuiContext& g = *GImGui;
10045
10046
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10047
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10048
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10049
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10050
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10051
    // while still correctly asserting on mid-frame key press events.
10052
24.1k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10053
24.1k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10054
24.1k
    IM_UNUSED(key_mods);
10055
10056
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10057
    //ErrorCheckEndFrameRecover();
10058
10059
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10060
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10061
24.1k
    if (g.CurrentWindowStack.Size != 1)
10062
0
    {
10063
0
        if (g.CurrentWindowStack.Size > 1)
10064
0
        {
10065
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10066
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10067
0
            IM_UNUSED(window);
10068
0
            while (g.CurrentWindowStack.Size > 1)
10069
0
                End();
10070
0
        }
10071
0
        else
10072
0
        {
10073
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10074
0
        }
10075
0
    }
10076
10077
24.1k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10078
24.1k
}
10079
10080
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10081
// Must be called during or before EndFrame().
10082
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10083
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10084
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10085
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10086
0
{
10087
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10088
0
    ImGuiContext& g = *GImGui;
10089
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10090
0
    {
10091
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10092
0
        ImGuiWindow* window = g.CurrentWindow;
10093
0
        if (g.CurrentWindowStack.Size == 1)
10094
0
        {
10095
0
            IM_ASSERT(window->IsFallbackWindow);
10096
0
            break;
10097
0
        }
10098
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10099
0
        {
10100
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10101
0
            EndChild();
10102
0
        }
10103
0
        else
10104
0
        {
10105
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10106
0
            End();
10107
0
        }
10108
0
    }
10109
0
}
10110
10111
// Must be called before End()/EndChild()
10112
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10113
0
{
10114
0
    ImGuiContext& g = *GImGui;
10115
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10116
0
    {
10117
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10118
0
        EndTable();
10119
0
    }
10120
10121
0
    ImGuiWindow* window = g.CurrentWindow;
10122
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10123
0
    IM_ASSERT(window != NULL);
10124
0
    while (g.CurrentTabBar != NULL) //-V1044
10125
0
    {
10126
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10127
0
        EndTabBar();
10128
0
    }
10129
0
    while (window->DC.TreeDepth > 0)
10130
0
    {
10131
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10132
0
        TreePop();
10133
0
    }
10134
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10135
0
    {
10136
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10137
0
        EndGroup();
10138
0
    }
10139
0
    while (window->IDStack.Size > 1)
10140
0
    {
10141
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10142
0
        PopID();
10143
0
    }
10144
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10145
0
    {
10146
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10147
0
        EndDisabled();
10148
0
    }
10149
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10150
0
    {
10151
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10152
0
        PopStyleColor();
10153
0
    }
10154
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10155
0
    {
10156
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10157
0
        PopItemFlag();
10158
0
    }
10159
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10160
0
    {
10161
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10162
0
        PopStyleVar();
10163
0
    }
10164
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10165
0
    {
10166
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10167
0
        PopFont();
10168
0
    }
10169
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10170
0
    {
10171
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10172
0
        PopFocusScope();
10173
0
    }
10174
0
}
10175
10176
// Save current stack sizes for later compare
10177
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10178
71.8k
{
10179
71.8k
    ImGuiContext& g = *ctx;
10180
71.8k
    ImGuiWindow* window = g.CurrentWindow;
10181
71.8k
    SizeOfIDStack = (short)window->IDStack.Size;
10182
71.8k
    SizeOfColorStack = (short)g.ColorStack.Size;
10183
71.8k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10184
71.8k
    SizeOfFontStack = (short)g.FontStack.Size;
10185
71.8k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10186
71.8k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10187
71.8k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10188
71.8k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10189
71.8k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10190
71.8k
}
10191
10192
// Compare to detect usage errors
10193
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10194
71.8k
{
10195
71.8k
    ImGuiContext& g = *ctx;
10196
71.8k
    ImGuiWindow* window = g.CurrentWindow;
10197
71.8k
    IM_UNUSED(window);
10198
10199
    // Window stacks
10200
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10201
71.8k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10202
10203
    // Global stacks
10204
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10205
71.8k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10206
71.8k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10207
71.8k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10208
71.8k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10209
71.8k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10210
71.8k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10211
71.8k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10212
71.8k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10213
71.8k
}
10214
10215
10216
//-----------------------------------------------------------------------------
10217
// [SECTION] LAYOUT
10218
//-----------------------------------------------------------------------------
10219
// - ItemSize()
10220
// - ItemAdd()
10221
// - SameLine()
10222
// - GetCursorScreenPos()
10223
// - SetCursorScreenPos()
10224
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10225
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10226
// - GetCursorStartPos()
10227
// - Indent()
10228
// - Unindent()
10229
// - SetNextItemWidth()
10230
// - PushItemWidth()
10231
// - PushMultiItemsWidths()
10232
// - PopItemWidth()
10233
// - CalcItemWidth()
10234
// - CalcItemSize()
10235
// - GetTextLineHeight()
10236
// - GetTextLineHeightWithSpacing()
10237
// - GetFrameHeight()
10238
// - GetFrameHeightWithSpacing()
10239
// - GetContentRegionMax()
10240
// - GetContentRegionMaxAbs() [Internal]
10241
// - GetContentRegionAvail(),
10242
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10243
// - BeginGroup()
10244
// - EndGroup()
10245
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10246
//-----------------------------------------------------------------------------
10247
10248
// Advance cursor given item size for layout.
10249
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10250
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10251
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10252
47.3k
{
10253
47.3k
    ImGuiContext& g = *GImGui;
10254
47.3k
    ImGuiWindow* window = g.CurrentWindow;
10255
47.3k
    if (window->SkipItems)
10256
0
        return;
10257
10258
    // We increase the height in this function to accommodate for baseline offset.
10259
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10260
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10261
47.3k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10262
10263
47.3k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10264
47.3k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10265
10266
    // Always align ourselves on pixel boundaries
10267
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10268
47.3k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10269
47.3k
    window->DC.CursorPosPrevLine.y = line_y1;
10270
47.3k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10271
47.3k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10272
47.3k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10273
47.3k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10274
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10275
10276
47.3k
    window->DC.PrevLineSize.y = line_height;
10277
47.3k
    window->DC.CurrLineSize.y = 0.0f;
10278
47.3k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10279
47.3k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10280
47.3k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10281
10282
    // Horizontal layout mode
10283
47.3k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10284
0
        SameLine();
10285
47.3k
}
10286
10287
// Declare item bounding box for clipping and interaction.
10288
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10289
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10290
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10291
144k
{
10292
144k
    ImGuiContext& g = *GImGui;
10293
144k
    ImGuiWindow* window = g.CurrentWindow;
10294
10295
    // Set item data
10296
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10297
144k
    g.LastItemData.ID = id;
10298
144k
    g.LastItemData.Rect = bb;
10299
144k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10300
144k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10301
144k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10302
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10303
10304
    // Directional navigation processing
10305
144k
    if (id != 0)
10306
97.9k
    {
10307
97.9k
        KeepAliveID(id);
10308
10309
        // Runs prior to clipping early-out
10310
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10311
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10312
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10313
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10314
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10315
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10316
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10317
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10318
97.9k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10319
49.0k
        {
10320
49.0k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10321
49.0k
            if (g.NavId == id || g.NavAnyRequest)
10322
3.46k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10323
590
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10324
590
                        NavProcessItem();
10325
49.0k
        }
10326
10327
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10328
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10329
        // READ THE FAQ: https://dearimgui.com/faq
10330
97.9k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10331
97.9k
    }
10332
144k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10333
144k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10334
10335
#ifdef IMGUI_ENABLE_TEST_ENGINE
10336
    if (id != 0)
10337
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10338
#endif
10339
10340
    // Clipping test
10341
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10342
    //const bool is_clipped = IsClippedEx(bb, id);
10343
    //if (is_clipped)
10344
    //    return false;
10345
144k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10346
144k
    if (!is_rect_visible)
10347
41.1k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10348
41.1k
            if (!g.LogEnabled)
10349
41.1k
                return false;
10350
10351
    // [DEBUG]
10352
103k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10353
103k
    if (id != 0 && id == g.DebugLocateId)
10354
0
        DebugLocateItemResolveWithLastItem();
10355
103k
#endif
10356
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10357
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10358
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10359
10360
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10361
103k
    if (is_rect_visible)
10362
103k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10363
103k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10364
746
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10365
103k
    return true;
10366
144k
}
10367
10368
// Gets back to previous line and continue with horizontal layout
10369
//      offset_from_start_x == 0 : follow right after previous item
10370
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10371
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10372
//      spacing_w >= 0           : enforce spacing amount
10373
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10374
0
{
10375
0
    ImGuiContext& g = *GImGui;
10376
0
    ImGuiWindow* window = g.CurrentWindow;
10377
0
    if (window->SkipItems)
10378
0
        return;
10379
10380
0
    if (offset_from_start_x != 0.0f)
10381
0
    {
10382
0
        if (spacing_w < 0.0f)
10383
0
            spacing_w = 0.0f;
10384
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10385
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10386
0
    }
10387
0
    else
10388
0
    {
10389
0
        if (spacing_w < 0.0f)
10390
0
            spacing_w = g.Style.ItemSpacing.x;
10391
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10392
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10393
0
    }
10394
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10395
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10396
0
    window->DC.IsSameLine = true;
10397
0
}
10398
10399
ImVec2 ImGui::GetCursorScreenPos()
10400
29.0k
{
10401
29.0k
    ImGuiWindow* window = GetCurrentWindowRead();
10402
29.0k
    return window->DC.CursorPos;
10403
29.0k
}
10404
10405
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10406
0
{
10407
0
    ImGuiWindow* window = GetCurrentWindow();
10408
0
    window->DC.CursorPos = pos;
10409
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10410
0
    window->DC.IsSetPos = true;
10411
0
}
10412
10413
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10414
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10415
ImVec2 ImGui::GetCursorPos()
10416
0
{
10417
0
    ImGuiWindow* window = GetCurrentWindowRead();
10418
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10419
0
}
10420
10421
float ImGui::GetCursorPosX()
10422
0
{
10423
0
    ImGuiWindow* window = GetCurrentWindowRead();
10424
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10425
0
}
10426
10427
float ImGui::GetCursorPosY()
10428
0
{
10429
0
    ImGuiWindow* window = GetCurrentWindowRead();
10430
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10431
0
}
10432
10433
void ImGui::SetCursorPos(const ImVec2& local_pos)
10434
0
{
10435
0
    ImGuiWindow* window = GetCurrentWindow();
10436
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10437
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10438
0
    window->DC.IsSetPos = true;
10439
0
}
10440
10441
void ImGui::SetCursorPosX(float x)
10442
0
{
10443
0
    ImGuiWindow* window = GetCurrentWindow();
10444
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10445
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10446
0
    window->DC.IsSetPos = true;
10447
0
}
10448
10449
void ImGui::SetCursorPosY(float y)
10450
0
{
10451
0
    ImGuiWindow* window = GetCurrentWindow();
10452
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10453
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10454
0
    window->DC.IsSetPos = true;
10455
0
}
10456
10457
ImVec2 ImGui::GetCursorStartPos()
10458
0
{
10459
0
    ImGuiWindow* window = GetCurrentWindowRead();
10460
0
    return window->DC.CursorStartPos - window->Pos;
10461
0
}
10462
10463
void ImGui::Indent(float indent_w)
10464
0
{
10465
0
    ImGuiContext& g = *GImGui;
10466
0
    ImGuiWindow* window = GetCurrentWindow();
10467
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10468
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10469
0
}
10470
10471
void ImGui::Unindent(float indent_w)
10472
0
{
10473
0
    ImGuiContext& g = *GImGui;
10474
0
    ImGuiWindow* window = GetCurrentWindow();
10475
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10476
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10477
0
}
10478
10479
// Affect large frame+labels widgets only.
10480
void ImGui::SetNextItemWidth(float item_width)
10481
0
{
10482
0
    ImGuiContext& g = *GImGui;
10483
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10484
0
    g.NextItemData.Width = item_width;
10485
0
}
10486
10487
// FIXME: Remove the == 0.0f behavior?
10488
void ImGui::PushItemWidth(float item_width)
10489
0
{
10490
0
    ImGuiContext& g = *GImGui;
10491
0
    ImGuiWindow* window = g.CurrentWindow;
10492
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10493
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10494
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10495
0
}
10496
10497
void ImGui::PushMultiItemsWidths(int components, float w_full)
10498
0
{
10499
0
    ImGuiContext& g = *GImGui;
10500
0
    ImGuiWindow* window = g.CurrentWindow;
10501
0
    const ImGuiStyle& style = g.Style;
10502
0
    const float w_item_one  = ImMax(1.0f, IM_TRUNC((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10503
0
    const float w_item_last = ImMax(1.0f, IM_TRUNC(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10504
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10505
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10506
0
    for (int i = 0; i < components - 2; i++)
10507
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10508
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10509
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10510
0
}
10511
10512
void ImGui::PopItemWidth()
10513
0
{
10514
0
    ImGuiWindow* window = GetCurrentWindow();
10515
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10516
0
    window->DC.ItemWidthStack.pop_back();
10517
0
}
10518
10519
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10520
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10521
float ImGui::CalcItemWidth()
10522
0
{
10523
0
    ImGuiContext& g = *GImGui;
10524
0
    ImGuiWindow* window = g.CurrentWindow;
10525
0
    float w;
10526
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10527
0
        w = g.NextItemData.Width;
10528
0
    else
10529
0
        w = window->DC.ItemWidth;
10530
0
    if (w < 0.0f)
10531
0
    {
10532
0
        float region_max_x = GetContentRegionMaxAbs().x;
10533
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10534
0
    }
10535
0
    w = IM_TRUNC(w);
10536
0
    return w;
10537
0
}
10538
10539
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10540
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10541
// Note that only CalcItemWidth() is publicly exposed.
10542
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10543
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10544
0
{
10545
0
    ImGuiContext& g = *GImGui;
10546
0
    ImGuiWindow* window = g.CurrentWindow;
10547
10548
0
    ImVec2 region_max;
10549
0
    if (size.x < 0.0f || size.y < 0.0f)
10550
0
        region_max = GetContentRegionMaxAbs();
10551
10552
0
    if (size.x == 0.0f)
10553
0
        size.x = default_w;
10554
0
    else if (size.x < 0.0f)
10555
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10556
10557
0
    if (size.y == 0.0f)
10558
0
        size.y = default_h;
10559
0
    else if (size.y < 0.0f)
10560
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10561
10562
0
    return size;
10563
0
}
10564
10565
float ImGui::GetTextLineHeight()
10566
0
{
10567
0
    ImGuiContext& g = *GImGui;
10568
0
    return g.FontSize;
10569
0
}
10570
10571
float ImGui::GetTextLineHeightWithSpacing()
10572
23.6k
{
10573
23.6k
    ImGuiContext& g = *GImGui;
10574
23.6k
    return g.FontSize + g.Style.ItemSpacing.y;
10575
23.6k
}
10576
10577
float ImGui::GetFrameHeight()
10578
132
{
10579
132
    ImGuiContext& g = *GImGui;
10580
132
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10581
132
}
10582
10583
float ImGui::GetFrameHeightWithSpacing()
10584
0
{
10585
0
    ImGuiContext& g = *GImGui;
10586
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10587
0
}
10588
10589
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10590
10591
// FIXME: This is in window space (not screen space!).
10592
ImVec2 ImGui::GetContentRegionMax()
10593
0
{
10594
0
    ImGuiContext& g = *GImGui;
10595
0
    ImGuiWindow* window = g.CurrentWindow;
10596
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10597
0
    return mx - window->Pos;
10598
0
}
10599
10600
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10601
ImVec2 ImGui::GetContentRegionMaxAbs()
10602
23.6k
{
10603
23.6k
    ImGuiContext& g = *GImGui;
10604
23.6k
    ImGuiWindow* window = g.CurrentWindow;
10605
23.6k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10606
23.6k
    return mx;
10607
23.6k
}
10608
10609
ImVec2 ImGui::GetContentRegionAvail()
10610
23.6k
{
10611
23.6k
    ImGuiWindow* window = GImGui->CurrentWindow;
10612
23.6k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10613
23.6k
}
10614
10615
// In window space (not screen space!)
10616
ImVec2 ImGui::GetWindowContentRegionMin()
10617
0
{
10618
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10619
0
    return window->ContentRegionRect.Min - window->Pos;
10620
0
}
10621
10622
ImVec2 ImGui::GetWindowContentRegionMax()
10623
23.6k
{
10624
23.6k
    ImGuiWindow* window = GImGui->CurrentWindow;
10625
23.6k
    return window->ContentRegionRect.Max - window->Pos;
10626
23.6k
}
10627
10628
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10629
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10630
// FIXME-OPT: Could we safely early out on ->SkipItems?
10631
void ImGui::BeginGroup()
10632
0
{
10633
0
    ImGuiContext& g = *GImGui;
10634
0
    ImGuiWindow* window = g.CurrentWindow;
10635
10636
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10637
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10638
0
    group_data.WindowID = window->ID;
10639
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10640
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10641
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10642
0
    group_data.BackupIndent = window->DC.Indent;
10643
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10644
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10645
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10646
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10647
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10648
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
10649
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10650
0
    group_data.EmitItem = true;
10651
10652
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10653
0
    window->DC.Indent = window->DC.GroupOffset;
10654
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10655
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10656
0
    if (g.LogEnabled)
10657
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10658
0
}
10659
10660
void ImGui::EndGroup()
10661
0
{
10662
0
    ImGuiContext& g = *GImGui;
10663
0
    ImGuiWindow* window = g.CurrentWindow;
10664
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10665
10666
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10667
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10668
10669
0
    if (window->DC.IsSetPos)
10670
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10671
10672
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10673
10674
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10675
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
10676
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10677
0
    window->DC.Indent = group_data.BackupIndent;
10678
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10679
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10680
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10681
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
10682
0
    if (g.LogEnabled)
10683
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10684
10685
0
    if (!group_data.EmitItem)
10686
0
    {
10687
0
        g.GroupStack.pop_back();
10688
0
        return;
10689
0
    }
10690
10691
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10692
0
    ItemSize(group_bb.GetSize());
10693
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10694
10695
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10696
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10697
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10698
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10699
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10700
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10701
0
    if (group_contains_curr_active_id)
10702
0
        g.LastItemData.ID = g.ActiveId;
10703
0
    else if (group_contains_prev_active_id)
10704
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10705
0
    g.LastItemData.Rect = group_bb;
10706
10707
    // Forward Hovered flag
10708
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10709
0
    if (group_contains_curr_hovered_id)
10710
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10711
10712
    // Forward Edited flag
10713
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10714
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10715
10716
    // Forward Deactivated flag
10717
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10718
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10719
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10720
10721
0
    g.GroupStack.pop_back();
10722
0
    if (g.DebugShowGroupRects)
10723
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10724
0
}
10725
10726
10727
//-----------------------------------------------------------------------------
10728
// [SECTION] SCROLLING
10729
//-----------------------------------------------------------------------------
10730
10731
// Helper to snap on edges when aiming at an item very close to the edge,
10732
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10733
// When we refactor the scrolling API this may be configurable with a flag?
10734
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10735
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10736
0
{
10737
0
    if (target <= snap_min + snap_threshold)
10738
0
        return ImLerp(snap_min, target, center_ratio);
10739
0
    if (target >= snap_max - snap_threshold)
10740
0
        return ImLerp(target, snap_max, center_ratio);
10741
0
    return target;
10742
0
}
10743
10744
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10745
71.8k
{
10746
71.8k
    ImVec2 scroll = window->Scroll;
10747
71.8k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10748
215k
    for (int axis = 0; axis < 2; axis++)
10749
143k
    {
10750
143k
        if (window->ScrollTarget[axis] < FLT_MAX)
10751
11.7k
        {
10752
11.7k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10753
11.7k
            float scroll_target = window->ScrollTarget[axis];
10754
11.7k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10755
0
            {
10756
0
                float snap_min = 0.0f;
10757
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10758
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10759
0
            }
10760
11.7k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10761
11.7k
        }
10762
143k
        scroll[axis] = IM_TRUNC(ImMax(scroll[axis], 0.0f));
10763
143k
        if (!window->Collapsed && !window->SkipItems)
10764
142k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10765
143k
    }
10766
71.8k
    return scroll;
10767
71.8k
}
10768
10769
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10770
0
{
10771
0
    ImGuiContext& g = *GImGui;
10772
0
    ImGuiWindow* window = g.CurrentWindow;
10773
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10774
0
}
10775
10776
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10777
0
{
10778
0
    ScrollToRectEx(window, item_rect, flags);
10779
0
}
10780
10781
// Scroll to keep newly navigated item fully into view
10782
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10783
7
{
10784
7
    ImGuiContext& g = *GImGui;
10785
7
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10786
7
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10787
7
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10788
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10789
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10790
10791
    // Check that only one behavior is selected per axis
10792
7
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10793
7
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10794
10795
    // Defaults
10796
7
    ImGuiScrollFlags in_flags = flags;
10797
7
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10798
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10799
7
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10800
4
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10801
10802
7
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10803
7
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10804
7
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10805
7
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10806
10807
7
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10808
0
    {
10809
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10810
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10811
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10812
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10813
0
    }
10814
7
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10815
0
    {
10816
0
        if (can_be_fully_visible_x)
10817
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10818
0
        else
10819
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10820
0
    }
10821
10822
7
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10823
0
    {
10824
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10825
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10826
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10827
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10828
0
    }
10829
7
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10830
0
    {
10831
0
        if (can_be_fully_visible_y)
10832
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10833
0
        else
10834
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10835
0
    }
10836
10837
7
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10838
7
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10839
10840
    // Also scroll parent window to keep us into view if necessary
10841
7
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10842
0
    {
10843
        // FIXME-SCROLL: May be an option?
10844
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10845
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10846
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10847
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10848
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10849
0
    }
10850
10851
7
    return delta_scroll;
10852
7
}
10853
10854
float ImGui::GetScrollX()
10855
33.9k
{
10856
33.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
10857
33.9k
    return window->Scroll.x;
10858
33.9k
}
10859
10860
float ImGui::GetScrollY()
10861
33.9k
{
10862
33.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
10863
33.9k
    return window->Scroll.y;
10864
33.9k
}
10865
10866
float ImGui::GetScrollMaxX()
10867
0
{
10868
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10869
0
    return window->ScrollMax.x;
10870
0
}
10871
10872
float ImGui::GetScrollMaxY()
10873
0
{
10874
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10875
0
    return window->ScrollMax.y;
10876
0
}
10877
10878
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10879
2.61k
{
10880
2.61k
    window->ScrollTarget.x = scroll_x;
10881
2.61k
    window->ScrollTargetCenterRatio.x = 0.0f;
10882
2.61k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10883
2.61k
}
10884
10885
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10886
9.20k
{
10887
9.20k
    window->ScrollTarget.y = scroll_y;
10888
9.20k
    window->ScrollTargetCenterRatio.y = 0.0f;
10889
9.20k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10890
9.20k
}
10891
10892
void ImGui::SetScrollX(float scroll_x)
10893
2.58k
{
10894
2.58k
    ImGuiContext& g = *GImGui;
10895
2.58k
    SetScrollX(g.CurrentWindow, scroll_x);
10896
2.58k
}
10897
10898
void ImGui::SetScrollY(float scroll_y)
10899
9.19k
{
10900
9.19k
    ImGuiContext& g = *GImGui;
10901
9.19k
    SetScrollY(g.CurrentWindow, scroll_y);
10902
9.19k
}
10903
10904
// Note that a local position will vary depending on initial scroll value,
10905
// This is a little bit confusing so bear with us:
10906
//  - local_pos = (absolution_pos - window->Pos)
10907
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10908
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10909
//  - They mostly exist because of legacy API.
10910
// Following the rules above, when trying to work with scrolling code, consider that:
10911
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10912
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10913
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10914
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10915
0
{
10916
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10917
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10918
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10919
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10920
0
}
10921
10922
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10923
0
{
10924
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10925
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10926
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10927
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10928
0
}
10929
10930
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10931
0
{
10932
0
    ImGuiContext& g = *GImGui;
10933
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10934
0
}
10935
10936
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10937
0
{
10938
0
    ImGuiContext& g = *GImGui;
10939
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10940
0
}
10941
10942
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10943
void ImGui::SetScrollHereX(float center_x_ratio)
10944
0
{
10945
0
    ImGuiContext& g = *GImGui;
10946
0
    ImGuiWindow* window = g.CurrentWindow;
10947
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10948
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10949
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10950
10951
    // Tweak: snap on edges when aiming at an item very close to the edge
10952
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10953
0
}
10954
10955
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10956
void ImGui::SetScrollHereY(float center_y_ratio)
10957
0
{
10958
0
    ImGuiContext& g = *GImGui;
10959
0
    ImGuiWindow* window = g.CurrentWindow;
10960
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10961
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10962
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10963
10964
    // Tweak: snap on edges when aiming at an item very close to the edge
10965
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10966
0
}
10967
10968
//-----------------------------------------------------------------------------
10969
// [SECTION] TOOLTIPS
10970
//-----------------------------------------------------------------------------
10971
10972
bool ImGui::BeginTooltip()
10973
29
{
10974
29
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10975
29
}
10976
10977
bool ImGui::BeginItemTooltip()
10978
0
{
10979
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10980
0
        return false;
10981
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10982
0
}
10983
10984
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10985
29
{
10986
29
    ImGuiContext& g = *GImGui;
10987
10988
29
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10989
0
    {
10990
        // Drag and Drop tooltips are positioning differently than other tooltips:
10991
        // - offset visibility to increase visibility around mouse.
10992
        // - never clamp within outer viewport boundary.
10993
        // We call SetNextWindowPos() to enforce position and disable clamping.
10994
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
10995
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10996
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
10997
0
        SetNextWindowPos(tooltip_pos);
10998
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10999
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11000
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11001
0
    }
11002
11003
29
    char window_name[16];
11004
29
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11005
29
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11006
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11007
0
            if (window->Active)
11008
0
            {
11009
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11010
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
11011
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11012
0
            }
11013
29
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11014
29
    Begin(window_name, NULL, flags | extra_window_flags);
11015
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11016
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11017
    //if (!ret)
11018
    //    End();
11019
    //return ret;
11020
29
    return true;
11021
29
}
11022
11023
void ImGui::EndTooltip()
11024
29
{
11025
29
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11026
29
    End();
11027
29
}
11028
11029
void ImGui::SetTooltip(const char* fmt, ...)
11030
0
{
11031
0
    va_list args;
11032
0
    va_start(args, fmt);
11033
0
    SetTooltipV(fmt, args);
11034
0
    va_end(args);
11035
0
}
11036
11037
void ImGui::SetTooltipV(const char* fmt, va_list args)
11038
0
{
11039
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11040
0
        return;
11041
0
    TextV(fmt, args);
11042
0
    EndTooltip();
11043
0
}
11044
11045
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11046
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11047
void ImGui::SetItemTooltip(const char* fmt, ...)
11048
0
{
11049
0
    va_list args;
11050
0
    va_start(args, fmt);
11051
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11052
0
        SetTooltipV(fmt, args);
11053
0
    va_end(args);
11054
0
}
11055
11056
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11057
0
{
11058
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11059
0
        SetTooltipV(fmt, args);
11060
0
}
11061
11062
11063
//-----------------------------------------------------------------------------
11064
// [SECTION] POPUPS
11065
//-----------------------------------------------------------------------------
11066
11067
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11068
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11069
0
{
11070
0
    ImGuiContext& g = *GImGui;
11071
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11072
0
    {
11073
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11074
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11075
0
        IM_ASSERT(id == 0);
11076
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11077
0
            return g.OpenPopupStack.Size > 0;
11078
0
        else
11079
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11080
0
    }
11081
0
    else
11082
0
    {
11083
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11084
0
        {
11085
            // Return true if the popup is open anywhere in the popup stack
11086
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11087
0
                if (popup_data.PopupId == id)
11088
0
                    return true;
11089
0
            return false;
11090
0
        }
11091
0
        else
11092
0
        {
11093
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11094
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11095
0
        }
11096
0
    }
11097
0
}
11098
11099
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11100
0
{
11101
0
    ImGuiContext& g = *GImGui;
11102
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11103
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11104
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11105
0
    return IsPopupOpen(id, popup_flags);
11106
0
}
11107
11108
// Also see FindBlockingModal(NULL)
11109
ImGuiWindow* ImGui::GetTopMostPopupModal()
11110
72.3k
{
11111
72.3k
    ImGuiContext& g = *GImGui;
11112
72.3k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11113
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11114
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11115
0
                return popup;
11116
72.3k
    return NULL;
11117
72.3k
}
11118
11119
// See Demo->Stacked Modal to confirm what this is for.
11120
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11121
24.1k
{
11122
24.1k
    ImGuiContext& g = *GImGui;
11123
24.1k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11124
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11125
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11126
0
                return popup;
11127
24.1k
    return NULL;
11128
24.1k
}
11129
11130
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11131
0
{
11132
0
    ImGuiContext& g = *GImGui;
11133
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11134
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11135
0
    OpenPopupEx(id, popup_flags);
11136
0
}
11137
11138
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11139
0
{
11140
0
    OpenPopupEx(id, popup_flags);
11141
0
}
11142
11143
// Mark popup as open (toggle toward open state).
11144
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11145
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11146
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11147
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11148
0
{
11149
0
    ImGuiContext& g = *GImGui;
11150
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11151
0
    const int current_stack_size = g.BeginPopupStack.Size;
11152
11153
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11154
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11155
0
            return;
11156
11157
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11158
0
    popup_ref.PopupId = id;
11159
0
    popup_ref.Window = NULL;
11160
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
11161
0
    popup_ref.OpenFrameCount = g.FrameCount;
11162
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11163
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11164
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11165
11166
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11167
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11168
0
    {
11169
0
        g.OpenPopupStack.push_back(popup_ref);
11170
0
    }
11171
0
    else
11172
0
    {
11173
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
11174
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
11175
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
11176
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
11177
0
        {
11178
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11179
0
        }
11180
0
        else
11181
0
        {
11182
            // Close child popups if any, then flag popup for open/reopen
11183
0
            ClosePopupToLevel(current_stack_size, false);
11184
0
            g.OpenPopupStack.push_back(popup_ref);
11185
0
        }
11186
11187
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11188
        // This is equivalent to what ClosePopupToLevel() does.
11189
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11190
        //    FocusWindow(parent_window);
11191
0
    }
11192
0
}
11193
11194
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11195
// This function closes any popups that are over 'ref_window'.
11196
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11197
5.97k
{
11198
5.97k
    ImGuiContext& g = *GImGui;
11199
5.97k
    if (g.OpenPopupStack.Size == 0)
11200
5.97k
        return;
11201
11202
    // Don't close our own child popup windows.
11203
0
    int popup_count_to_keep = 0;
11204
0
    if (ref_window)
11205
0
    {
11206
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11207
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11208
0
        {
11209
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11210
0
            if (!popup.Window)
11211
0
                continue;
11212
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11213
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
11214
0
                continue;
11215
11216
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11217
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
11218
            //     Window -> Popup1 -> Popup2 -> Popup3
11219
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11220
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11221
0
            bool ref_window_is_descendent_of_popup = false;
11222
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11223
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11224
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11225
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11226
0
                    {
11227
0
                        ref_window_is_descendent_of_popup = true;
11228
0
                        break;
11229
0
                    }
11230
0
            if (!ref_window_is_descendent_of_popup)
11231
0
                break;
11232
0
        }
11233
0
    }
11234
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11235
0
    {
11236
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11237
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11238
0
    }
11239
0
}
11240
11241
void ImGui::ClosePopupsExceptModals()
11242
0
{
11243
0
    ImGuiContext& g = *GImGui;
11244
11245
0
    int popup_count_to_keep;
11246
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11247
0
    {
11248
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11249
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11250
0
            break;
11251
0
    }
11252
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11253
0
        ClosePopupToLevel(popup_count_to_keep, true);
11254
0
}
11255
11256
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11257
0
{
11258
0
    ImGuiContext& g = *GImGui;
11259
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
11260
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11261
11262
    // Trim open popup stack
11263
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
11264
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
11265
0
    g.OpenPopupStack.resize(remaining);
11266
11267
0
    if (restore_focus_to_window_under_popup)
11268
0
    {
11269
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
11270
0
        if (focus_window && !focus_window->WasActive && popup_window)
11271
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11272
0
        else
11273
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11274
0
    }
11275
0
}
11276
11277
// Close the popup we have begin-ed into.
11278
void ImGui::CloseCurrentPopup()
11279
0
{
11280
0
    ImGuiContext& g = *GImGui;
11281
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11282
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11283
0
        return;
11284
11285
    // Closing a menu closes its top-most parent popup (unless a modal)
11286
0
    while (popup_idx > 0)
11287
0
    {
11288
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11289
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11290
0
        bool close_parent = false;
11291
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11292
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11293
0
                close_parent = true;
11294
0
        if (!close_parent)
11295
0
            break;
11296
0
        popup_idx--;
11297
0
    }
11298
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11299
0
    ClosePopupToLevel(popup_idx, true);
11300
11301
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11302
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11303
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11304
0
    if (ImGuiWindow* window = g.NavWindow)
11305
0
        window->DC.NavHideHighlightOneFrame = true;
11306
0
}
11307
11308
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11309
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11310
0
{
11311
0
    ImGuiContext& g = *GImGui;
11312
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11313
0
    {
11314
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11315
0
        return false;
11316
0
    }
11317
11318
0
    char name[20];
11319
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11320
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
11321
0
    else
11322
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11323
11324
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11325
0
    bool is_open = Begin(name, NULL, flags);
11326
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11327
0
        EndPopup();
11328
11329
0
    return is_open;
11330
0
}
11331
11332
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11333
0
{
11334
0
    ImGuiContext& g = *GImGui;
11335
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11336
0
    {
11337
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11338
0
        return false;
11339
0
    }
11340
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11341
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11342
0
    return BeginPopupEx(id, flags);
11343
0
}
11344
11345
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11346
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11347
// - *p_open set back to false in BeginPopupModal() when popup is not open.
11348
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11349
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11350
0
{
11351
0
    ImGuiContext& g = *GImGui;
11352
0
    ImGuiWindow* window = g.CurrentWindow;
11353
0
    const ImGuiID id = window->GetID(name);
11354
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11355
0
    {
11356
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11357
0
        if (p_open && *p_open)
11358
0
            *p_open = false;
11359
0
        return false;
11360
0
    }
11361
11362
    // Center modal windows by default for increased visibility
11363
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11364
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11365
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11366
0
    {
11367
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11368
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11369
0
    }
11370
11371
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11372
0
    const bool is_open = Begin(name, p_open, flags);
11373
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11374
0
    {
11375
0
        EndPopup();
11376
0
        if (is_open)
11377
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11378
0
        return false;
11379
0
    }
11380
0
    return is_open;
11381
0
}
11382
11383
void ImGui::EndPopup()
11384
0
{
11385
0
    ImGuiContext& g = *GImGui;
11386
0
    ImGuiWindow* window = g.CurrentWindow;
11387
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11388
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11389
11390
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11391
0
    if (g.NavWindow == window)
11392
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11393
11394
    // Child-popups don't need to be laid out
11395
0
    IM_ASSERT(g.WithinEndChild == false);
11396
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11397
0
        g.WithinEndChild = true;
11398
0
    End();
11399
0
    g.WithinEndChild = false;
11400
0
}
11401
11402
// Helper to open a popup if mouse button is released over the item
11403
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11404
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11405
0
{
11406
0
    ImGuiContext& g = *GImGui;
11407
0
    ImGuiWindow* window = g.CurrentWindow;
11408
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11409
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11410
0
    {
11411
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11412
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11413
0
        OpenPopupEx(id, popup_flags);
11414
0
    }
11415
0
}
11416
11417
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11418
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11419
// - To create a popup with a specific identifier, pass it in str_id.
11420
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11421
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11422
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11423
//   This is essentially the same as:
11424
//       id = str_id ? GetID(str_id) : GetItemID();
11425
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11426
//       return BeginPopup(id);
11427
//   Which is essentially the same as:
11428
//       id = str_id ? GetID(str_id) : GetItemID();
11429
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11430
//           OpenPopup(id);
11431
//       return BeginPopup(id);
11432
//   The main difference being that this is tweaked to avoid computing the ID twice.
11433
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11434
0
{
11435
0
    ImGuiContext& g = *GImGui;
11436
0
    ImGuiWindow* window = g.CurrentWindow;
11437
0
    if (window->SkipItems)
11438
0
        return false;
11439
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11440
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11441
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11442
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11443
0
        OpenPopupEx(id, popup_flags);
11444
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11445
0
}
11446
11447
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11448
0
{
11449
0
    ImGuiContext& g = *GImGui;
11450
0
    ImGuiWindow* window = g.CurrentWindow;
11451
0
    if (!str_id)
11452
0
        str_id = "window_context";
11453
0
    ImGuiID id = window->GetID(str_id);
11454
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11455
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11456
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11457
0
            OpenPopupEx(id, popup_flags);
11458
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11459
0
}
11460
11461
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11462
0
{
11463
0
    ImGuiContext& g = *GImGui;
11464
0
    ImGuiWindow* window = g.CurrentWindow;
11465
0
    if (!str_id)
11466
0
        str_id = "void_context";
11467
0
    ImGuiID id = window->GetID(str_id);
11468
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11469
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11470
0
        if (GetTopMostPopupModal() == NULL)
11471
0
            OpenPopupEx(id, popup_flags);
11472
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11473
0
}
11474
11475
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11476
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11477
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11478
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11479
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11480
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11481
29
{
11482
29
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11483
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11484
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11485
11486
    // Combo Box policy (we want a connecting edge)
11487
29
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11488
0
    {
11489
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11490
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11491
0
        {
11492
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11493
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11494
0
                continue;
11495
0
            ImVec2 pos;
11496
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11497
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11498
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11499
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11500
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11501
0
                continue;
11502
0
            *last_dir = dir;
11503
0
            return pos;
11504
0
        }
11505
0
    }
11506
11507
    // Tooltip and Default popup policy
11508
    // (Always first try the direction we used on the last frame, if any)
11509
29
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11510
29
    {
11511
29
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11512
29
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11513
29
        {
11514
29
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11515
29
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11516
0
                continue;
11517
11518
29
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11519
29
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11520
11521
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11522
29
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11523
0
                continue;
11524
29
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11525
0
                continue;
11526
11527
29
            ImVec2 pos;
11528
29
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11529
29
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11530
11531
            // Clamp top-left corner of popup
11532
29
            pos.x = ImMax(pos.x, r_outer.Min.x);
11533
29
            pos.y = ImMax(pos.y, r_outer.Min.y);
11534
11535
29
            *last_dir = dir;
11536
29
            return pos;
11537
29
        }
11538
29
    }
11539
11540
    // Fallback when not enough room:
11541
0
    *last_dir = ImGuiDir_None;
11542
11543
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11544
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11545
0
        return ref_pos + ImVec2(2, 2);
11546
11547
    // Otherwise try to keep within display
11548
0
    ImVec2 pos = ref_pos;
11549
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11550
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11551
0
    return pos;
11552
0
}
11553
11554
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11555
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11556
29
{
11557
29
    ImGuiContext& g = *GImGui;
11558
29
    ImRect r_screen;
11559
29
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11560
0
    {
11561
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11562
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11563
0
        r_screen.Min = monitor.WorkPos;
11564
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11565
0
    }
11566
29
    else
11567
29
    {
11568
        // Use the full viewport area (not work area) for popups
11569
29
        r_screen = window->Viewport->GetMainRect();
11570
29
    }
11571
29
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11572
29
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11573
29
    return r_screen;
11574
29
}
11575
11576
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11577
29
{
11578
29
    ImGuiContext& g = *GImGui;
11579
11580
29
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11581
29
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11582
0
    {
11583
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11584
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11585
0
        ImGuiWindow* parent_window = window->ParentWindow;
11586
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11587
0
        ImRect r_avoid;
11588
0
        if (parent_window->DC.MenuBarAppending)
11589
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11590
0
        else
11591
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11592
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11593
0
    }
11594
29
    if (window->Flags & ImGuiWindowFlags_Popup)
11595
0
    {
11596
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11597
0
    }
11598
29
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11599
29
    {
11600
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11601
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11602
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11603
29
        IM_ASSERT(g.CurrentWindow == window);
11604
29
        const float scale = g.Style.MouseCursorScale;
11605
29
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11606
29
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11607
29
        ImRect r_avoid;
11608
29
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11609
3
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11610
26
        else
11611
26
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11612
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11613
29
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11614
29
    }
11615
0
    IM_ASSERT(0);
11616
0
    return window->Pos;
11617
29
}
11618
11619
//-----------------------------------------------------------------------------
11620
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11621
//-----------------------------------------------------------------------------
11622
11623
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11624
// In our terminology those should be interchangeable, yet right now this is super confusing.
11625
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11626
11627
void ImGui::SetNavWindow(ImGuiWindow* window)
11628
5.90k
{
11629
5.90k
    ImGuiContext& g = *GImGui;
11630
5.90k
    if (g.NavWindow != window)
11631
5.90k
    {
11632
5.90k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11633
5.90k
        g.NavWindow = window;
11634
5.90k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11635
5.90k
    }
11636
5.90k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11637
5.90k
    NavUpdateAnyRequestFlag();
11638
5.90k
}
11639
11640
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11641
1.96k
{
11642
1.96k
    ImGuiContext& g = *GImGui;
11643
1.96k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11644
1.96k
}
11645
11646
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11647
224
{
11648
224
    ImGuiContext& g = *GImGui;
11649
224
    IM_ASSERT(g.NavWindow != NULL);
11650
224
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11651
224
    g.NavId = id;
11652
224
    g.NavLayer = nav_layer;
11653
224
    g.NavFocusScopeId = focus_scope_id;
11654
224
    g.NavWindow->NavLastIds[nav_layer] = id;
11655
224
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11656
11657
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11658
224
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11659
224
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11660
224
}
11661
11662
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11663
0
{
11664
0
    ImGuiContext& g = *GImGui;
11665
0
    IM_ASSERT(id != 0);
11666
11667
0
    if (g.NavWindow != window)
11668
0
       SetNavWindow(window);
11669
11670
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11671
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11672
0
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11673
0
    g.NavId = id;
11674
0
    g.NavLayer = nav_layer;
11675
0
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11676
0
    window->NavLastIds[nav_layer] = id;
11677
0
    if (g.LastItemData.ID == id)
11678
0
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11679
11680
0
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11681
0
        g.NavDisableMouseHover = true;
11682
0
    else
11683
0
        g.NavDisableHighlight = true;
11684
11685
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11686
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11687
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11688
0
}
11689
11690
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11691
8
{
11692
8
    if (ImFabs(dx) > ImFabs(dy))
11693
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11694
8
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11695
8
}
11696
11697
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11698
16
{
11699
16
    if (cand_max < curr_min)
11700
8
        return cand_max - curr_min;
11701
8
    if (curr_max < cand_min)
11702
0
        return cand_min - curr_max;
11703
8
    return 0.0f;
11704
8
}
11705
11706
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11707
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11708
470
{
11709
470
    ImGuiContext& g = *GImGui;
11710
470
    ImGuiWindow* window = g.CurrentWindow;
11711
470
    if (g.NavLayer != window->DC.NavLayerCurrent)
11712
462
        return false;
11713
11714
    // FIXME: Those are not good variables names
11715
8
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11716
8
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11717
8
    g.NavScoringDebugCount++;
11718
11719
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11720
8
    if (window->ParentWindow == g.NavWindow)
11721
0
    {
11722
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11723
0
        if (!window->ClipRect.Overlaps(cand))
11724
0
            return false;
11725
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11726
0
    }
11727
11728
    // Compute distance between boxes
11729
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11730
8
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11731
8
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11732
8
    if (dby != 0.0f && dbx != 0.0f)
11733
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11734
8
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11735
11736
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11737
8
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11738
8
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11739
8
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11740
11741
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11742
8
    ImGuiDir quadrant;
11743
8
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11744
8
    if (dbx != 0.0f || dby != 0.0f)
11745
8
    {
11746
        // For non-overlapping boxes, use distance between boxes
11747
8
        dax = dbx;
11748
8
        day = dby;
11749
8
        dist_axial = dist_box;
11750
8
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11751
8
    }
11752
0
    else if (dcx != 0.0f || dcy != 0.0f)
11753
0
    {
11754
        // For overlapping boxes with different centers, use distance between centers
11755
0
        dax = dcx;
11756
0
        day = dcy;
11757
0
        dist_axial = dist_center;
11758
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11759
0
    }
11760
0
    else
11761
0
    {
11762
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11763
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11764
0
    }
11765
11766
8
    const ImGuiDir move_dir = g.NavMoveDir;
11767
#if IMGUI_DEBUG_NAV_SCORING
11768
    char buf[200];
11769
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11770
    {
11771
        if (quadrant == move_dir)
11772
        {
11773
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11774
            ImDrawList* draw_list = GetForegroundDrawList(window);
11775
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11776
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11777
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11778
        }
11779
    }
11780
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11781
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11782
    if (debug_hovering || debug_tty)
11783
    {
11784
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11785
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11786
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11787
        if (debug_hovering)
11788
        {
11789
            ImDrawList* draw_list = GetForegroundDrawList(window);
11790
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11791
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11792
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11793
            draw_list->AddText(cand.Max, ~0U, buf);
11794
        }
11795
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11796
    }
11797
#endif
11798
11799
    // Is it in the quadrant we're interested in moving to?
11800
8
    bool new_best = false;
11801
8
    if (quadrant == move_dir)
11802
8
    {
11803
        // Does it beat the current best candidate?
11804
8
        if (dist_box < result->DistBox)
11805
8
        {
11806
8
            result->DistBox = dist_box;
11807
8
            result->DistCenter = dist_center;
11808
8
            return true;
11809
8
        }
11810
0
        if (dist_box == result->DistBox)
11811
0
        {
11812
            // Try using distance between center points to break ties
11813
0
            if (dist_center < result->DistCenter)
11814
0
            {
11815
0
                result->DistCenter = dist_center;
11816
0
                new_best = true;
11817
0
            }
11818
0
            else if (dist_center == result->DistCenter)
11819
0
            {
11820
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11821
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11822
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11823
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11824
0
                    new_best = true;
11825
0
            }
11826
0
        }
11827
0
    }
11828
11829
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11830
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11831
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11832
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11833
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11834
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11835
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11836
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11837
0
            {
11838
0
                result->DistAxial = dist_axial;
11839
0
                new_best = true;
11840
0
            }
11841
11842
0
    return new_best;
11843
8
}
11844
11845
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11846
13
{
11847
13
    ImGuiContext& g = *GImGui;
11848
13
    ImGuiWindow* window = g.CurrentWindow;
11849
13
    result->Window = window;
11850
13
    result->ID = g.LastItemData.ID;
11851
13
    result->FocusScopeId = g.CurrentFocusScopeId;
11852
13
    result->InFlags = g.LastItemData.InFlags;
11853
13
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11854
13
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
11855
0
    {
11856
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11857
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11858
0
    }
11859
13
}
11860
11861
// True when current work location may be scrolled horizontally when moving left / right.
11862
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11863
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11864
119k
{
11865
119k
    ImGuiContext& g = *GImGui;
11866
119k
    ImGuiWindow* window = g.CurrentWindow;
11867
119k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11868
119k
}
11869
11870
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11871
// This is called after LastItemData is set, but NextItemData is also still valid.
11872
static void ImGui::NavProcessItem()
11873
590
{
11874
590
    ImGuiContext& g = *GImGui;
11875
590
    ImGuiWindow* window = g.CurrentWindow;
11876
590
    const ImGuiID id = g.LastItemData.ID;
11877
590
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11878
11879
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11880
590
    if (window->DC.NavIsScrollPushableX == false)
11881
0
    {
11882
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11883
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11884
0
    }
11885
590
    const ImRect nav_bb = g.LastItemData.NavRect;
11886
11887
    // Process Init Request
11888
590
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11889
0
    {
11890
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11891
0
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11892
0
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11893
0
        {
11894
0
            NavApplyItemToResult(&g.NavInitResult);
11895
0
        }
11896
0
        if (candidate_for_nav_default_focus)
11897
0
        {
11898
0
            g.NavInitRequest = false; // Found a match, clear request
11899
0
            NavUpdateAnyRequestFlag();
11900
0
        }
11901
0
    }
11902
11903
    // Process Move Request (scoring for navigation)
11904
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11905
590
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11906
455
    {
11907
455
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
11908
455
        if (is_tabbing)
11909
33
        {
11910
33
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11911
33
        }
11912
422
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11913
422
        {
11914
422
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11915
422
            if (NavScoreItem(result))
11916
4
                NavApplyItemToResult(result);
11917
11918
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11919
422
            const float VISIBLE_RATIO = 0.70f;
11920
422
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11921
48
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11922
48
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11923
4
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11924
422
        }
11925
455
    }
11926
11927
    // Update information for currently focused/navigated item
11928
590
    if (g.NavId == id)
11929
140
    {
11930
140
        if (g.NavWindow != window)
11931
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11932
140
        g.NavLayer = window->DC.NavLayerCurrent;
11933
140
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11934
140
        g.NavIdIsAlive = true;
11935
140
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
11936
0
        {
11937
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11938
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11939
0
        }
11940
140
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11941
140
    }
11942
590
}
11943
11944
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11945
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11946
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11947
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11948
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11949
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11950
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11951
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11952
33
{
11953
33
    ImGuiContext& g = *GImGui;
11954
11955
33
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11956
33
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11957
28
            return;
11958
11959
    // - Can always land on an item when using API call.
11960
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11961
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11962
5
    bool can_stop;
11963
5
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11964
0
        can_stop = true;
11965
5
    else
11966
5
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11967
11968
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11969
5
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11970
5
    if (g.NavTabbingDir == +1)
11971
5
    {
11972
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11973
5
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
11974
5
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11975
5
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11976
0
            NavMoveRequestResolveWithLastItem(result);
11977
5
        else if (g.NavId == id)
11978
3
            g.NavTabbingCounter = 1;
11979
5
    }
11980
0
    else if (g.NavTabbingDir == -1)
11981
0
    {
11982
        // Tab Backward
11983
0
        if (g.NavId == id)
11984
0
        {
11985
0
            if (result->ID)
11986
0
            {
11987
0
                g.NavMoveScoringItems = false;
11988
0
                NavUpdateAnyRequestFlag();
11989
0
            }
11990
0
        }
11991
0
        else if (can_stop)
11992
0
        {
11993
            // Keep applying until reaching NavId
11994
0
            NavApplyItemToResult(result);
11995
0
        }
11996
0
    }
11997
0
    else if (g.NavTabbingDir == 0)
11998
0
    {
11999
0
        if (can_stop && g.NavId == id)
12000
0
            NavMoveRequestResolveWithLastItem(result);
12001
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12002
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12003
0
    }
12004
5
}
12005
12006
bool ImGui::NavMoveRequestButNoResultYet()
12007
19.9k
{
12008
19.9k
    ImGuiContext& g = *GImGui;
12009
19.9k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12010
19.9k
}
12011
12012
// FIXME: ScoringRect is not set
12013
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12014
1.64k
{
12015
1.64k
    ImGuiContext& g = *GImGui;
12016
1.64k
    IM_ASSERT(g.NavWindow != NULL);
12017
12018
1.64k
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12019
111
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12020
12021
1.64k
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12022
1.64k
    g.NavMoveDir = move_dir;
12023
1.64k
    g.NavMoveDirForDebug = move_dir;
12024
1.64k
    g.NavMoveClipDir = clip_dir;
12025
1.64k
    g.NavMoveFlags = move_flags;
12026
1.64k
    g.NavMoveScrollFlags = scroll_flags;
12027
1.64k
    g.NavMoveForwardToNextFrame = false;
12028
1.64k
    g.NavMoveKeyMods = g.IO.KeyMods;
12029
1.64k
    g.NavMoveResultLocal.Clear();
12030
1.64k
    g.NavMoveResultLocalVisible.Clear();
12031
1.64k
    g.NavMoveResultOther.Clear();
12032
1.64k
    g.NavTabbingCounter = 0;
12033
1.64k
    g.NavTabbingResultFirst.Clear();
12034
1.64k
    NavUpdateAnyRequestFlag();
12035
1.64k
}
12036
12037
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12038
0
{
12039
0
    ImGuiContext& g = *GImGui;
12040
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12041
0
    NavApplyItemToResult(result);
12042
0
    NavUpdateAnyRequestFlag();
12043
0
}
12044
12045
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12046
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12047
0
{
12048
0
    ImGuiContext& g = *GImGui;
12049
0
    g.NavMoveScoringItems = false;
12050
0
    g.LastItemData.ID = tree_node_data->ID;
12051
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12052
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12053
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12054
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12055
0
    NavUpdateAnyRequestFlag();
12056
0
}
12057
12058
void ImGui::NavMoveRequestCancel()
12059
176
{
12060
176
    ImGuiContext& g = *GImGui;
12061
176
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12062
176
    NavUpdateAnyRequestFlag();
12063
176
}
12064
12065
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12066
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12067
0
{
12068
0
    ImGuiContext& g = *GImGui;
12069
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12070
0
    NavMoveRequestCancel();
12071
0
    g.NavMoveForwardToNextFrame = true;
12072
0
    g.NavMoveDir = move_dir;
12073
0
    g.NavMoveClipDir = clip_dir;
12074
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12075
0
    g.NavMoveScrollFlags = scroll_flags;
12076
0
}
12077
12078
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12079
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12080
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12081
0
{
12082
0
    ImGuiContext& g = *GImGui;
12083
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12084
12085
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12086
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12087
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12088
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12089
0
}
12090
12091
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12092
// This way we could find the last focused window among our children. It would be much less confusing this way?
12093
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12094
17.2k
{
12095
17.2k
    ImGuiWindow* parent = nav_window;
12096
30.5k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12097
13.3k
        parent = parent->ParentWindow;
12098
17.2k
    if (parent && parent != nav_window)
12099
13.3k
        parent->NavLastChildNavWindow = nav_window;
12100
17.2k
}
12101
12102
// Restore the last focused child.
12103
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12104
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12105
0
{
12106
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12107
0
        return window->NavLastChildNavWindow;
12108
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12109
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12110
0
            return tab->Window;
12111
0
    return window;
12112
0
}
12113
12114
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12115
0
{
12116
0
    ImGuiContext& g = *GImGui;
12117
0
    if (layer == ImGuiNavLayer_Main)
12118
0
    {
12119
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
12120
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12121
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12122
0
        if (prev_nav_window)
12123
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12124
0
    }
12125
0
    ImGuiWindow* window = g.NavWindow;
12126
0
    if (window->NavLastIds[layer] != 0)
12127
0
    {
12128
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12129
0
    }
12130
0
    else
12131
0
    {
12132
0
        g.NavLayer = layer;
12133
0
        NavInitWindow(window, true);
12134
0
    }
12135
0
}
12136
12137
void ImGui::NavRestoreHighlightAfterMove()
12138
589
{
12139
589
    ImGuiContext& g = *GImGui;
12140
589
    g.NavDisableHighlight = false;
12141
589
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12142
589
}
12143
12144
static inline void ImGui::NavUpdateAnyRequestFlag()
12145
31.8k
{
12146
31.8k
    ImGuiContext& g = *GImGui;
12147
31.8k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12148
31.8k
    if (g.NavAnyRequest)
12149
31.8k
        IM_ASSERT(g.NavWindow != NULL);
12150
31.8k
}
12151
12152
// This needs to be called before we submit any widget (aka in or before Begin)
12153
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12154
3
{
12155
    // FIXME: ChildWindow test here is wrong for docking
12156
3
    ImGuiContext& g = *GImGui;
12157
3
    IM_ASSERT(window == g.NavWindow);
12158
12159
3
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12160
0
    {
12161
0
        g.NavId = 0;
12162
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12163
0
        return;
12164
0
    }
12165
12166
3
    bool init_for_nav = false;
12167
3
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12168
3
        init_for_nav = true;
12169
3
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12170
3
    if (init_for_nav)
12171
3
    {
12172
3
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12173
3
        g.NavInitRequest = true;
12174
3
        g.NavInitRequestFromMove = false;
12175
3
        g.NavInitResult.ID = 0;
12176
3
        NavUpdateAnyRequestFlag();
12177
3
    }
12178
0
    else
12179
0
    {
12180
0
        g.NavId = window->NavLastIds[0];
12181
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12182
0
    }
12183
3
}
12184
12185
static ImVec2 ImGui::NavCalcPreferredRefPos()
12186
29
{
12187
29
    ImGuiContext& g = *GImGui;
12188
29
    ImGuiWindow* window = g.NavWindow;
12189
29
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12190
29
    {
12191
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12192
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12193
        // In theory we could move that +1.0f offset in OpenPopupEx()
12194
29
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12195
29
        return ImVec2(p.x + 1.0f, p.y);
12196
29
    }
12197
0
    else
12198
0
    {
12199
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12200
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12201
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12202
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12203
0
        {
12204
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12205
0
            rect_rel.Translate(window->Scroll - next_scroll);
12206
0
        }
12207
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12208
0
        ImGuiViewport* viewport = window->Viewport;
12209
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12210
0
    }
12211
29
}
12212
12213
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12214
0
{
12215
0
    ImGuiContext& g = *GImGui;
12216
0
    float repeat_delay, repeat_rate;
12217
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12218
12219
0
    ImGuiKey key_less, key_more;
12220
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12221
0
    {
12222
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12223
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12224
0
    }
12225
0
    else
12226
0
    {
12227
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12228
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12229
0
    }
12230
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12231
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12232
0
        amount = 0.0f;
12233
0
    return amount;
12234
0
}
12235
12236
static void ImGui::NavUpdate()
12237
24.1k
{
12238
24.1k
    ImGuiContext& g = *GImGui;
12239
24.1k
    ImGuiIO& io = g.IO;
12240
12241
24.1k
    io.WantSetMousePos = false;
12242
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12243
12244
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12245
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12246
24.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12247
24.1k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12248
24.1k
    if (nav_gamepad_active)
12249
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12250
0
            if (IsKeyDown(key))
12251
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12252
24.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12253
24.1k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12254
24.1k
    if (nav_keyboard_active)
12255
24.1k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12256
168k
            if (IsKeyDown(key))
12257
10.7k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12258
12259
    // Process navigation init request (select first/default focus)
12260
24.1k
    g.NavJustMovedToId = 0;
12261
24.1k
    if (g.NavInitResult.ID != 0)
12262
0
        NavInitRequestApplyResult();
12263
24.1k
    g.NavInitRequest = false;
12264
24.1k
    g.NavInitRequestFromMove = false;
12265
24.1k
    g.NavInitResult.ID = 0;
12266
12267
    // Process navigation move request
12268
24.1k
    if (g.NavMoveSubmitted)
12269
1.52k
        NavMoveRequestApplyResult();
12270
24.1k
    g.NavTabbingCounter = 0;
12271
24.1k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12272
12273
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12274
24.1k
    bool set_mouse_pos = false;
12275
24.1k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12276
17
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12277
17
            set_mouse_pos = true;
12278
24.1k
    g.NavMousePosDirty = false;
12279
24.1k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12280
12281
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12282
24.1k
    if (g.NavWindow)
12283
17.2k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12284
24.1k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12285
202
        g.NavWindow->NavLastChildNavWindow = NULL;
12286
12287
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12288
24.1k
    NavUpdateWindowing();
12289
12290
    // Set output flags for user application
12291
24.1k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12292
24.1k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12293
12294
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12295
24.1k
    NavUpdateCancelRequest();
12296
12297
    // Process manual activation request
12298
24.1k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12299
24.1k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12300
24.1k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12301
3.88k
    {
12302
3.88k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
12303
3.88k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
12304
3.88k
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
12305
3.88k
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
12306
3.88k
        if (g.ActiveId == 0 && activate_pressed)
12307
4
        {
12308
4
            g.NavActivateId = g.NavId;
12309
4
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12310
4
        }
12311
3.88k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12312
4
        {
12313
4
            g.NavActivateId = g.NavId;
12314
4
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12315
4
        }
12316
3.88k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12317
217
            g.NavActivateDownId = g.NavId;
12318
3.88k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12319
8
            g.NavActivatePressedId = g.NavId;
12320
3.88k
    }
12321
24.1k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12322
0
        g.NavDisableHighlight = true;
12323
24.1k
    if (g.NavActivateId != 0)
12324
24.1k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12325
12326
    // Process programmatic activation request
12327
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12328
24.1k
    if (g.NavNextActivateId != 0)
12329
0
    {
12330
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12331
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12332
0
    }
12333
24.1k
    g.NavNextActivateId = 0;
12334
12335
    // Process move requests
12336
24.1k
    NavUpdateCreateMoveRequest();
12337
24.1k
    if (g.NavMoveDir == ImGuiDir_None)
12338
22.5k
        NavUpdateCreateTabbingRequest();
12339
24.1k
    NavUpdateAnyRequestFlag();
12340
24.1k
    g.NavIdIsAlive = false;
12341
12342
    // Scrolling
12343
24.1k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12344
17.2k
    {
12345
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12346
17.2k
        ImGuiWindow* window = g.NavWindow;
12347
17.2k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12348
17.2k
        const ImGuiDir move_dir = g.NavMoveDir;
12349
17.2k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12350
35
        {
12351
35
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12352
35
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12353
35
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12354
0
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12355
35
        }
12356
12357
        // *Normal* Manual scroll with LStick
12358
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12359
17.2k
        if (nav_gamepad_active)
12360
0
        {
12361
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12362
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12363
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12364
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12365
0
            if (scroll_dir.y != 0.0f)
12366
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12367
0
        }
12368
17.2k
    }
12369
12370
    // Always prioritize mouse highlight if navigation is disabled
12371
24.1k
    if (!nav_keyboard_active && !nav_gamepad_active)
12372
0
    {
12373
0
        g.NavDisableHighlight = true;
12374
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12375
0
    }
12376
12377
    // Update mouse position if requested
12378
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12379
24.1k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12380
0
        TeleportMousePos(NavCalcPreferredRefPos());
12381
12382
    // [DEBUG]
12383
24.1k
    g.NavScoringDebugCount = 0;
12384
#if IMGUI_DEBUG_NAV_RECTS
12385
    if (ImGuiWindow* debug_window = g.NavWindow)
12386
    {
12387
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12388
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12389
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12390
    }
12391
#endif
12392
24.1k
}
12393
12394
void ImGui::NavInitRequestApplyResult()
12395
0
{
12396
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12397
0
    ImGuiContext& g = *GImGui;
12398
0
    if (!g.NavWindow)
12399
0
        return;
12400
12401
0
    ImGuiNavItemData* result = &g.NavInitResult;
12402
0
    if (g.NavId != result->ID)
12403
0
    {
12404
0
        g.NavJustMovedToId = result->ID;
12405
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12406
0
        g.NavJustMovedToKeyMods = 0;
12407
0
    }
12408
12409
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12410
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12411
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12412
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12413
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12414
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12415
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12416
0
    if (g.NavInitRequestFromMove)
12417
0
        NavRestoreHighlightAfterMove();
12418
0
}
12419
12420
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12421
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12422
1.53k
{
12423
    // Bias initial rect
12424
1.53k
    ImGuiContext& g = *GImGui;
12425
1.53k
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12426
12427
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12428
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12429
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12430
1.53k
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12431
1.53k
    {
12432
1.53k
        if (preferred_pos_rel.x == FLT_MAX)
12433
956
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12434
1.53k
        if (preferred_pos_rel.y == FLT_MAX)
12435
611
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12436
1.53k
    }
12437
12438
    // Apply general bias on the other axis
12439
1.53k
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12440
605
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12441
930
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12442
930
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12443
1.53k
}
12444
12445
void ImGui::NavUpdateCreateMoveRequest()
12446
24.1k
{
12447
24.1k
    ImGuiContext& g = *GImGui;
12448
24.1k
    ImGuiIO& io = g.IO;
12449
24.1k
    ImGuiWindow* window = g.NavWindow;
12450
24.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12451
24.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12452
12453
24.1k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12454
0
    {
12455
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12456
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12457
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12458
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12459
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12460
0
    }
12461
24.1k
    else
12462
24.1k
    {
12463
        // Initiate directional inputs request
12464
24.1k
        g.NavMoveDir = ImGuiDir_None;
12465
24.1k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12466
24.1k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12467
24.1k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12468
17.2k
        {
12469
17.2k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12470
17.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12471
17.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12472
17.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12473
17.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12474
17.2k
        }
12475
24.1k
        g.NavMoveClipDir = g.NavMoveDir;
12476
24.1k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12477
24.1k
    }
12478
12479
    // Update PageUp/PageDown/Home/End scroll
12480
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12481
24.1k
    float scoring_rect_offset_y = 0.0f;
12482
24.1k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12483
15.9k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12484
24.1k
    if (scoring_rect_offset_y != 0.0f)
12485
261
    {
12486
261
        g.NavScoringNoClipRect = window->InnerRect;
12487
261
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12488
261
    }
12489
12490
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12491
#if IMGUI_DEBUG_NAV_SCORING
12492
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12493
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12494
    if (io.KeyCtrl)
12495
    {
12496
        if (g.NavMoveDir == ImGuiDir_None)
12497
            g.NavMoveDir = g.NavMoveDirForDebug;
12498
        g.NavMoveClipDir = g.NavMoveDir;
12499
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12500
    }
12501
#endif
12502
12503
    // Submit
12504
24.1k
    g.NavMoveForwardToNextFrame = false;
12505
24.1k
    if (g.NavMoveDir != ImGuiDir_None)
12506
1.53k
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12507
12508
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12509
24.1k
    if (g.NavMoveSubmitted && g.NavId == 0)
12510
1.12k
    {
12511
1.12k
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12512
1.12k
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12513
1.12k
        g.NavInitResult.ID = 0;
12514
1.12k
        g.NavDisableHighlight = false;
12515
1.12k
    }
12516
12517
    // When using gamepad, we project the reference nav bounding box into window visible area.
12518
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12519
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12520
24.1k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12521
0
    {
12522
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12523
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12524
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12525
12526
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12527
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12528
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12529
12530
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12531
0
        {
12532
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12533
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12534
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12535
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12536
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12537
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12538
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12539
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12540
0
            g.NavId = 0;
12541
0
        }
12542
0
    }
12543
12544
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12545
24.1k
    ImRect scoring_rect;
12546
24.1k
    if (window != NULL)
12547
17.2k
    {
12548
17.2k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12549
17.2k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12550
17.2k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12551
17.2k
        if (g.NavMoveSubmitted)
12552
1.53k
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12553
17.2k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12554
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12555
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12556
17.2k
    }
12557
24.1k
    g.NavScoringRect = scoring_rect;
12558
24.1k
    g.NavScoringNoClipRect.Add(scoring_rect);
12559
24.1k
}
12560
12561
void ImGui::NavUpdateCreateTabbingRequest()
12562
22.5k
{
12563
22.5k
    ImGuiContext& g = *GImGui;
12564
22.5k
    ImGuiWindow* window = g.NavWindow;
12565
22.5k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12566
22.5k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12567
6.89k
        return;
12568
12569
15.6k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12570
15.6k
    if (!tab_pressed)
12571
15.5k
        return;
12572
12573
    // Initiate tabbing request
12574
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12575
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12576
111
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12577
111
    if (nav_keyboard_active)
12578
111
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12579
0
    else
12580
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12581
111
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12582
111
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12583
111
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12584
111
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12585
111
    g.NavTabbingCounter = -1;
12586
111
}
12587
12588
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12589
void ImGui::NavMoveRequestApplyResult()
12590
1.52k
{
12591
1.52k
    ImGuiContext& g = *GImGui;
12592
#if IMGUI_DEBUG_NAV_SCORING
12593
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12594
        return;
12595
#endif
12596
12597
    // Select which result to use
12598
1.52k
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12599
12600
    // Tabbing forward wrap
12601
1.52k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12602
102
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12603
3
            result = &g.NavTabbingResultFirst;
12604
12605
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12606
1.52k
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12607
1.52k
    if (result == NULL)
12608
1.52k
    {
12609
1.52k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12610
99
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12611
1.52k
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12612
368
            NavRestoreHighlightAfterMove();
12613
1.52k
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12614
1.52k
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12615
1.52k
        return;
12616
1.52k
    }
12617
12618
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12619
7
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12620
4
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12621
0
            result = &g.NavMoveResultLocalVisible;
12622
12623
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12624
7
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12625
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12626
0
            result = &g.NavMoveResultOther;
12627
7
    IM_ASSERT(g.NavWindow && result->Window);
12628
12629
    // Scroll to keep newly navigated item fully into view.
12630
7
    if (g.NavLayer == ImGuiNavLayer_Main)
12631
7
    {
12632
7
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12633
7
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12634
12635
7
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12636
0
        {
12637
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12638
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12639
0
            SetScrollY(result->Window, scroll_target);
12640
0
        }
12641
7
    }
12642
12643
7
    if (g.NavWindow != result->Window)
12644
0
    {
12645
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12646
0
        g.NavWindow = result->Window;
12647
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12648
0
    }
12649
7
    if (g.ActiveId != result->ID)
12650
7
        ClearActiveID();
12651
12652
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12653
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
12654
7
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12655
4
    {
12656
4
        g.NavJustMovedToId = result->ID;
12657
4
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12658
4
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12659
4
    }
12660
12661
    // Apply new NavID/Focus
12662
7
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12663
7
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12664
7
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12665
7
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12666
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12667
12668
    // Restore last preferred position for current axis
12669
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12670
7
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
12671
4
    {
12672
4
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12673
4
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12674
4
    }
12675
12676
    // Tabbing: Activates Inputable, otherwise only Focus
12677
7
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12678
3
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12679
12680
    // Activate
12681
7
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12682
0
    {
12683
0
        g.NavNextActivateId = result->ID;
12684
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12685
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12686
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12687
0
    }
12688
12689
    // Enable nav highlight
12690
7
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12691
7
        NavRestoreHighlightAfterMove();
12692
7
}
12693
12694
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12695
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12696
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12697
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12698
static void ImGui::NavUpdateCancelRequest()
12699
24.1k
{
12700
24.1k
    ImGuiContext& g = *GImGui;
12701
24.1k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12702
24.1k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12703
24.1k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12704
23.7k
        return;
12705
12706
318
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12707
318
    if (g.ActiveId != 0)
12708
0
    {
12709
0
        ClearActiveID();
12710
0
    }
12711
318
    else if (g.NavLayer != ImGuiNavLayer_Main)
12712
0
    {
12713
        // Leave the "menu" layer
12714
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12715
0
        NavRestoreHighlightAfterMove();
12716
0
    }
12717
318
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12718
214
    {
12719
        // Exit child window
12720
214
        ImGuiWindow* child_window = g.NavWindow;
12721
214
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12722
214
        IM_ASSERT(child_window->ChildId != 0);
12723
214
        ImRect child_rect = child_window->Rect();
12724
214
        FocusWindow(parent_window);
12725
214
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12726
214
        NavRestoreHighlightAfterMove();
12727
214
    }
12728
104
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12729
0
    {
12730
        // Close open popup/menu
12731
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12732
0
    }
12733
104
    else
12734
104
    {
12735
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12736
104
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12737
36
            g.NavWindow->NavLastIds[0] = 0;
12738
104
        g.NavId = 0;
12739
104
    }
12740
318
}
12741
12742
// Handle PageUp/PageDown/Home/End keys
12743
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12744
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12745
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12746
static float ImGui::NavUpdatePageUpPageDown()
12747
15.9k
{
12748
15.9k
    ImGuiContext& g = *GImGui;
12749
15.9k
    ImGuiWindow* window = g.NavWindow;
12750
15.9k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12751
0
        return 0.0f;
12752
12753
15.9k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12754
15.9k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12755
15.9k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12756
15.9k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12757
15.9k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12758
14.6k
        return 0.0f;
12759
12760
1.31k
    if (g.NavLayer != ImGuiNavLayer_Main)
12761
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12762
12763
1.31k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12764
8
    {
12765
        // Fallback manual-scroll when window has no navigable item
12766
8
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12767
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12768
8
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12769
2
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12770
6
        else if (home_pressed)
12771
0
            SetScrollY(window, 0.0f);
12772
6
        else if (end_pressed)
12773
1
            SetScrollY(window, window->ScrollMax.y);
12774
8
    }
12775
1.30k
    else
12776
1.30k
    {
12777
1.30k
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12778
1.30k
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12779
1.30k
        float nav_scoring_rect_offset_y = 0.0f;
12780
1.30k
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12781
33
        {
12782
33
            nav_scoring_rect_offset_y = -page_offset_y;
12783
33
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12784
33
            g.NavMoveClipDir = ImGuiDir_Up;
12785
33
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12786
33
        }
12787
1.27k
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12788
228
        {
12789
228
            nav_scoring_rect_offset_y = +page_offset_y;
12790
228
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12791
228
            g.NavMoveClipDir = ImGuiDir_Down;
12792
228
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12793
228
        }
12794
1.04k
        else if (home_pressed)
12795
2
        {
12796
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12797
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12798
            // Preserve current horizontal position if we have any.
12799
2
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12800
2
            if (nav_rect_rel.IsInverted())
12801
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12802
2
            g.NavMoveDir = ImGuiDir_Down;
12803
2
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12804
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12805
2
        }
12806
1.04k
        else if (end_pressed)
12807
1
        {
12808
1
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12809
1
            if (nav_rect_rel.IsInverted())
12810
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12811
1
            g.NavMoveDir = ImGuiDir_Up;
12812
1
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12813
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12814
1
        }
12815
1.30k
        return nav_scoring_rect_offset_y;
12816
1.30k
    }
12817
8
    return 0.0f;
12818
1.31k
}
12819
12820
static void ImGui::NavEndFrame()
12821
24.1k
{
12822
24.1k
    ImGuiContext& g = *GImGui;
12823
12824
    // Show CTRL+TAB list window
12825
24.1k
    if (g.NavWindowingTarget != NULL)
12826
0
        NavUpdateWindowingOverlay();
12827
12828
    // Perform wrap-around in menus
12829
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12830
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12831
24.1k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12832
0
        NavUpdateCreateWrappingRequest();
12833
24.1k
}
12834
12835
static void ImGui::NavUpdateCreateWrappingRequest()
12836
0
{
12837
0
    ImGuiContext& g = *GImGui;
12838
0
    ImGuiWindow* window = g.NavWindow;
12839
12840
0
    bool do_forward = false;
12841
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12842
0
    ImGuiDir clip_dir = g.NavMoveDir;
12843
12844
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12845
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12846
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12847
0
    {
12848
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12849
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12850
0
        {
12851
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12852
0
            clip_dir = ImGuiDir_Up;
12853
0
        }
12854
0
        do_forward = true;
12855
0
    }
12856
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12857
0
    {
12858
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12859
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12860
0
        {
12861
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12862
0
            clip_dir = ImGuiDir_Down;
12863
0
        }
12864
0
        do_forward = true;
12865
0
    }
12866
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12867
0
    {
12868
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12869
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12870
0
        {
12871
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12872
0
            clip_dir = ImGuiDir_Left;
12873
0
        }
12874
0
        do_forward = true;
12875
0
    }
12876
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12877
0
    {
12878
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12879
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12880
0
        {
12881
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12882
0
            clip_dir = ImGuiDir_Right;
12883
0
        }
12884
0
        do_forward = true;
12885
0
    }
12886
0
    if (!do_forward)
12887
0
        return;
12888
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12889
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12890
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12891
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12892
0
}
12893
12894
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12895
0
{
12896
0
    ImGuiContext& g = *GImGui;
12897
0
    IM_UNUSED(g);
12898
0
    int order = window->FocusOrder;
12899
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12900
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12901
0
    return order;
12902
0
}
12903
12904
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12905
0
{
12906
0
    ImGuiContext& g = *GImGui;
12907
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12908
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12909
0
            return g.WindowsFocusOrder[i];
12910
0
    return NULL;
12911
0
}
12912
12913
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12914
0
{
12915
0
    ImGuiContext& g = *GImGui;
12916
0
    IM_ASSERT(g.NavWindowingTarget);
12917
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12918
0
        return;
12919
12920
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12921
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12922
0
    if (!window_target)
12923
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12924
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12925
0
    {
12926
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12927
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12928
0
    }
12929
0
    g.NavWindowingToggleLayer = false;
12930
0
}
12931
12932
// Windowing management mode
12933
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12934
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12935
static void ImGui::NavUpdateWindowing()
12936
24.1k
{
12937
24.1k
    ImGuiContext& g = *GImGui;
12938
24.1k
    ImGuiIO& io = g.IO;
12939
12940
24.1k
    ImGuiWindow* apply_focus_window = NULL;
12941
24.1k
    bool apply_toggle_layer = false;
12942
12943
24.1k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12944
24.1k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12945
24.1k
    if (!allow_windowing)
12946
0
        g.NavWindowingTarget = NULL;
12947
12948
    // Fade out
12949
24.1k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12950
0
    {
12951
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12952
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12953
0
            g.NavWindowingTargetAnim = NULL;
12954
0
    }
12955
12956
    // Start CTRL+Tab or Square+L/R window selection
12957
24.1k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12958
24.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12959
24.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12960
24.1k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12961
24.1k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12962
24.1k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12963
24.1k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12964
24.1k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12965
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12966
0
        {
12967
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12968
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12969
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12970
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12971
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12972
12973
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
12974
0
            if (keyboard_next_window || keyboard_prev_window)
12975
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
12976
0
        }
12977
12978
    // Gamepad update
12979
24.1k
    g.NavWindowingTimer += io.DeltaTime;
12980
24.1k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12981
0
    {
12982
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12983
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12984
12985
        // Select window to focus
12986
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12987
0
        if (focus_change_dir != 0)
12988
0
        {
12989
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12990
0
            g.NavWindowingHighlightAlpha = 1.0f;
12991
0
        }
12992
12993
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12994
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12995
0
        {
12996
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12997
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12998
0
                apply_toggle_layer = true;
12999
0
            else if (!g.NavWindowingToggleLayer)
13000
0
                apply_focus_window = g.NavWindowingTarget;
13001
0
            g.NavWindowingTarget = NULL;
13002
0
        }
13003
0
    }
13004
13005
    // Keyboard: Focus
13006
24.1k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13007
0
    {
13008
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13009
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13010
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13011
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13012
0
        if (keyboard_next_window || keyboard_prev_window)
13013
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13014
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13015
0
            apply_focus_window = g.NavWindowingTarget;
13016
0
    }
13017
13018
    // Keyboard: Press and Release ALT to toggle menu layer
13019
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
13020
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
13021
24.1k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
13022
0
    {
13023
0
        g.NavWindowingToggleLayer = true;
13024
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
13025
0
    }
13026
24.1k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13027
0
    {
13028
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13029
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13030
        // We cancel toggling nav layer if an owner has claimed the key.
13031
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13032
0
            g.NavWindowingToggleLayer = false;
13033
13034
        // Apply layer toggle on release
13035
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13036
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
13037
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13038
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13039
0
                    apply_toggle_layer = true;
13040
0
        if (!IsKeyDown(ImGuiMod_Alt))
13041
0
            g.NavWindowingToggleLayer = false;
13042
0
    }
13043
13044
    // Move window
13045
24.1k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13046
0
    {
13047
0
        ImVec2 nav_move_dir;
13048
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13049
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13050
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13051
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13052
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13053
0
        {
13054
0
            const float NAV_MOVE_SPEED = 800.0f;
13055
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13056
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13057
0
            g.NavDisableMouseHover = true;
13058
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13059
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13060
0
            {
13061
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13062
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13063
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13064
0
            }
13065
0
        }
13066
0
    }
13067
13068
    // Apply final focus
13069
24.1k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13070
0
    {
13071
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13072
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13073
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13074
0
        ClearActiveID();
13075
0
        NavRestoreHighlightAfterMove();
13076
0
        ClosePopupsOverWindow(apply_focus_window, false);
13077
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13078
0
        apply_focus_window = g.NavWindow;
13079
0
        if (apply_focus_window->NavLastIds[0] == 0)
13080
0
            NavInitWindow(apply_focus_window, false);
13081
13082
        // If the window has ONLY a menu layer (no main layer), select it directly
13083
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13084
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13085
        // the target window as already been previewed once.
13086
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13087
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13088
        // won't be valid.
13089
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13090
0
            g.NavLayer = ImGuiNavLayer_Menu;
13091
13092
        // Request OS level focus
13093
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13094
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13095
0
    }
13096
24.1k
    if (apply_focus_window)
13097
0
        g.NavWindowingTarget = NULL;
13098
13099
    // Apply menu/layer toggle
13100
24.1k
    if (apply_toggle_layer && g.NavWindow)
13101
0
    {
13102
0
        ClearActiveID();
13103
13104
        // Move to parent menu if necessary
13105
0
        ImGuiWindow* new_nav_window = g.NavWindow;
13106
0
        while (new_nav_window->ParentWindow
13107
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13108
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13109
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13110
0
            new_nav_window = new_nav_window->ParentWindow;
13111
0
        if (new_nav_window != g.NavWindow)
13112
0
        {
13113
0
            ImGuiWindow* old_nav_window = g.NavWindow;
13114
0
            FocusWindow(new_nav_window);
13115
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13116
0
        }
13117
13118
        // Toggle layer
13119
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13120
0
        if (new_nav_layer != g.NavLayer)
13121
0
        {
13122
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13123
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13124
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13125
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13126
0
            NavRestoreLayer(new_nav_layer);
13127
0
            NavRestoreHighlightAfterMove();
13128
0
        }
13129
0
    }
13130
24.1k
}
13131
13132
// Window has already passed the IsWindowNavFocusable()
13133
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13134
0
{
13135
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13136
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13137
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13138
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13139
0
    if (window->DockNodeAsHost)
13140
0
        return "(Dock node)"; // Not normally shown to user.
13141
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13142
0
}
13143
13144
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13145
void ImGui::NavUpdateWindowingOverlay()
13146
0
{
13147
0
    ImGuiContext& g = *GImGui;
13148
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13149
13150
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13151
0
        return;
13152
13153
0
    if (g.NavWindowingListWindow == NULL)
13154
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13155
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13156
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13157
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13158
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13159
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13160
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13161
0
    {
13162
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13163
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13164
0
        if (!IsWindowNavFocusable(window))
13165
0
            continue;
13166
0
        const char* label = window->Name;
13167
0
        if (label == FindRenderedTextEnd(label))
13168
0
            label = GetFallbackWindowNameForWindowingList(window);
13169
0
        Selectable(label, g.NavWindowingTarget == window);
13170
0
    }
13171
0
    End();
13172
0
    PopStyleVar();
13173
0
}
13174
13175
13176
//-----------------------------------------------------------------------------
13177
// [SECTION] DRAG AND DROP
13178
//-----------------------------------------------------------------------------
13179
13180
bool ImGui::IsDragDropActive()
13181
0
{
13182
0
    ImGuiContext& g = *GImGui;
13183
0
    return g.DragDropActive;
13184
0
}
13185
13186
void ImGui::ClearDragDrop()
13187
2
{
13188
2
    ImGuiContext& g = *GImGui;
13189
2
    g.DragDropActive = false;
13190
2
    g.DragDropPayload.Clear();
13191
2
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13192
2
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13193
2
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13194
2
    g.DragDropAcceptFrameCount = -1;
13195
13196
2
    g.DragDropPayloadBufHeap.clear();
13197
2
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13198
2
}
13199
13200
bool ImGui::BeginTooltipHidden()
13201
0
{
13202
0
    ImGuiContext& g = *GImGui;
13203
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13204
0
    SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
13205
0
    return ret;
13206
0
}
13207
13208
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13209
// If the item has an identifier:
13210
// - This assume/require the item to be activated (typically via ButtonBehavior).
13211
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13212
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13213
// If the item has no identifier:
13214
// - Currently always assume left mouse button.
13215
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13216
132
{
13217
132
    ImGuiContext& g = *GImGui;
13218
132
    ImGuiWindow* window = g.CurrentWindow;
13219
13220
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13221
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13222
132
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13223
13224
132
    bool source_drag_active = false;
13225
132
    ImGuiID source_id = 0;
13226
132
    ImGuiID source_parent_id = 0;
13227
132
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13228
132
    {
13229
132
        source_id = g.LastItemData.ID;
13230
132
        if (source_id != 0)
13231
132
        {
13232
            // Common path: items with ID
13233
132
            if (g.ActiveId != source_id)
13234
0
                return false;
13235
132
            if (g.ActiveIdMouseButton != -1)
13236
0
                mouse_button = g.ActiveIdMouseButton;
13237
132
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13238
0
                return false;
13239
132
            g.ActiveIdAllowOverlap = false;
13240
132
        }
13241
0
        else
13242
0
        {
13243
            // Uncommon path: items without ID
13244
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13245
0
                return false;
13246
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13247
0
                return false;
13248
13249
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13250
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13251
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13252
0
            {
13253
0
                IM_ASSERT(0);
13254
0
                return false;
13255
0
            }
13256
13257
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13258
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13259
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13260
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13261
            // Rely on keeping other window->LastItemXXX fields intact.
13262
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13263
0
            KeepAliveID(source_id);
13264
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13265
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13266
0
            {
13267
0
                SetActiveID(source_id, window);
13268
0
                FocusWindow(window);
13269
0
            }
13270
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13271
0
                g.ActiveIdAllowOverlap = is_hovered;
13272
0
        }
13273
132
        if (g.ActiveId != source_id)
13274
0
            return false;
13275
132
        source_parent_id = window->IDStack.back();
13276
132
        source_drag_active = IsMouseDragging(mouse_button);
13277
13278
        // Disable navigation and key inputs while dragging + cancel existing request if any
13279
132
        SetActiveIdUsingAllKeyboardKeys();
13280
132
    }
13281
0
    else
13282
0
    {
13283
0
        window = NULL;
13284
0
        source_id = ImHashStr("#SourceExtern");
13285
0
        source_drag_active = true;
13286
0
    }
13287
13288
132
    if (source_drag_active)
13289
16
    {
13290
16
        if (!g.DragDropActive)
13291
1
        {
13292
1
            IM_ASSERT(source_id != 0);
13293
1
            ClearDragDrop();
13294
1
            ImGuiPayload& payload = g.DragDropPayload;
13295
1
            payload.SourceId = source_id;
13296
1
            payload.SourceParentId = source_parent_id;
13297
1
            g.DragDropActive = true;
13298
1
            g.DragDropSourceFlags = flags;
13299
1
            g.DragDropMouseButton = mouse_button;
13300
1
            if (payload.SourceId == g.ActiveId)
13301
1
                g.ActiveIdNoClearOnFocusLoss = true;
13302
1
        }
13303
16
        g.DragDropSourceFrameCount = g.FrameCount;
13304
16
        g.DragDropWithinSource = true;
13305
13306
16
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13307
0
        {
13308
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13309
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13310
0
            bool ret;
13311
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13312
0
                ret = BeginTooltipHidden();
13313
0
            else
13314
0
                ret = BeginTooltip();
13315
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13316
0
            IM_UNUSED(ret);
13317
0
        }
13318
13319
16
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13320
16
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13321
13322
16
        return true;
13323
16
    }
13324
116
    return false;
13325
132
}
13326
13327
void ImGui::EndDragDropSource()
13328
16
{
13329
16
    ImGuiContext& g = *GImGui;
13330
16
    IM_ASSERT(g.DragDropActive);
13331
16
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13332
13333
16
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13334
0
        EndTooltip();
13335
13336
    // Discard the drag if have not called SetDragDropPayload()
13337
16
    if (g.DragDropPayload.DataFrameCount == -1)
13338
0
        ClearDragDrop();
13339
16
    g.DragDropWithinSource = false;
13340
16
}
13341
13342
// Use 'cond' to choose to submit payload on drag start or every frame
13343
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13344
16
{
13345
16
    ImGuiContext& g = *GImGui;
13346
16
    ImGuiPayload& payload = g.DragDropPayload;
13347
16
    if (cond == 0)
13348
16
        cond = ImGuiCond_Always;
13349
13350
16
    IM_ASSERT(type != NULL);
13351
16
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13352
16
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13353
16
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13354
16
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13355
13356
16
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13357
16
    {
13358
        // Copy payload
13359
16
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13360
16
        g.DragDropPayloadBufHeap.resize(0);
13361
16
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13362
0
        {
13363
            // Store in heap
13364
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13365
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13366
0
            memcpy(payload.Data, data, data_size);
13367
0
        }
13368
16
        else if (data_size > 0)
13369
16
        {
13370
            // Store locally
13371
16
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13372
16
            payload.Data = g.DragDropPayloadBufLocal;
13373
16
            memcpy(payload.Data, data, data_size);
13374
16
        }
13375
0
        else
13376
0
        {
13377
0
            payload.Data = NULL;
13378
0
        }
13379
16
        payload.DataSize = (int)data_size;
13380
16
    }
13381
16
    payload.DataFrameCount = g.FrameCount;
13382
13383
    // Return whether the payload has been accepted
13384
16
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13385
16
}
13386
13387
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13388
19
{
13389
19
    ImGuiContext& g = *GImGui;
13390
19
    if (!g.DragDropActive)
13391
0
        return false;
13392
13393
19
    ImGuiWindow* window = g.CurrentWindow;
13394
19
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13395
19
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13396
19
        return false;
13397
0
    IM_ASSERT(id != 0);
13398
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13399
0
        return false;
13400
0
    if (window->SkipItems)
13401
0
        return false;
13402
13403
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13404
0
    g.DragDropTargetRect = bb;
13405
0
    g.DragDropTargetId = id;
13406
0
    g.DragDropWithinTarget = true;
13407
0
    return true;
13408
0
}
13409
13410
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13411
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13412
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13413
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13414
bool ImGui::BeginDragDropTarget()
13415
0
{
13416
0
    ImGuiContext& g = *GImGui;
13417
0
    if (!g.DragDropActive)
13418
0
        return false;
13419
13420
0
    ImGuiWindow* window = g.CurrentWindow;
13421
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13422
0
        return false;
13423
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13424
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13425
0
        return false;
13426
13427
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13428
0
    ImGuiID id = g.LastItemData.ID;
13429
0
    if (id == 0)
13430
0
    {
13431
0
        id = window->GetIDFromRectangle(display_rect);
13432
0
        KeepAliveID(id);
13433
0
    }
13434
0
    if (g.DragDropPayload.SourceId == id)
13435
0
        return false;
13436
13437
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13438
0
    g.DragDropTargetRect = display_rect;
13439
0
    g.DragDropTargetId = id;
13440
0
    g.DragDropWithinTarget = true;
13441
0
    return true;
13442
0
}
13443
13444
bool ImGui::IsDragDropPayloadBeingAccepted()
13445
18
{
13446
18
    ImGuiContext& g = *GImGui;
13447
18
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13448
18
}
13449
13450
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13451
0
{
13452
0
    ImGuiContext& g = *GImGui;
13453
0
    ImGuiPayload& payload = g.DragDropPayload;
13454
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13455
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13456
0
    if (type != NULL && !payload.IsDataType(type))
13457
0
        return NULL;
13458
13459
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13460
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13461
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13462
0
    ImRect r = g.DragDropTargetRect;
13463
0
    float r_surface = r.GetWidth() * r.GetHeight();
13464
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13465
0
        return NULL;
13466
13467
0
    g.DragDropAcceptFlags = flags;
13468
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13469
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13470
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13471
13472
    // Render default drop visuals
13473
0
    payload.Preview = was_accepted_previously;
13474
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13475
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13476
0
        RenderDragDropTargetRect(r);
13477
13478
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13479
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13480
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13481
0
        return NULL;
13482
13483
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13484
0
    return &payload;
13485
0
}
13486
13487
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13488
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
13489
0
{
13490
0
    ImGuiContext& g = *GImGui;
13491
0
    ImGuiWindow* window = g.CurrentWindow;
13492
0
    ImRect bb_display = bb;
13493
0
    bb_display.ClipWith(window->ClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13494
0
    bb_display.Expand(3.5f);
13495
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
13496
0
    if (push_clip_rect)
13497
0
        window->DrawList->PushClipRectFullScreen();
13498
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13499
0
    if (push_clip_rect)
13500
0
        window->DrawList->PopClipRect();
13501
0
}
13502
13503
const ImGuiPayload* ImGui::GetDragDropPayload()
13504
0
{
13505
0
    ImGuiContext& g = *GImGui;
13506
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13507
0
}
13508
13509
void ImGui::EndDragDropTarget()
13510
0
{
13511
0
    ImGuiContext& g = *GImGui;
13512
0
    IM_ASSERT(g.DragDropActive);
13513
0
    IM_ASSERT(g.DragDropWithinTarget);
13514
0
    g.DragDropWithinTarget = false;
13515
13516
    // Clear drag and drop state payload right after delivery
13517
0
    if (g.DragDropPayload.Delivery)
13518
0
        ClearDragDrop();
13519
0
}
13520
13521
//-----------------------------------------------------------------------------
13522
// [SECTION] LOGGING/CAPTURING
13523
//-----------------------------------------------------------------------------
13524
// All text output from the interface can be captured into tty/file/clipboard.
13525
// By default, tree nodes are automatically opened during logging.
13526
//-----------------------------------------------------------------------------
13527
13528
// Pass text data straight to log (without being displayed)
13529
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13530
0
{
13531
0
    if (g.LogFile)
13532
0
    {
13533
0
        g.LogBuffer.Buf.resize(0);
13534
0
        g.LogBuffer.appendfv(fmt, args);
13535
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13536
0
    }
13537
0
    else
13538
0
    {
13539
0
        g.LogBuffer.appendfv(fmt, args);
13540
0
    }
13541
0
}
13542
13543
void ImGui::LogText(const char* fmt, ...)
13544
0
{
13545
0
    ImGuiContext& g = *GImGui;
13546
0
    if (!g.LogEnabled)
13547
0
        return;
13548
13549
0
    va_list args;
13550
0
    va_start(args, fmt);
13551
0
    LogTextV(g, fmt, args);
13552
0
    va_end(args);
13553
0
}
13554
13555
void ImGui::LogTextV(const char* fmt, va_list args)
13556
0
{
13557
0
    ImGuiContext& g = *GImGui;
13558
0
    if (!g.LogEnabled)
13559
0
        return;
13560
13561
0
    LogTextV(g, fmt, args);
13562
0
}
13563
13564
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13565
// We split text into individual lines to add current tree level padding
13566
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13567
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13568
0
{
13569
0
    ImGuiContext& g = *GImGui;
13570
0
    ImGuiWindow* window = g.CurrentWindow;
13571
13572
0
    const char* prefix = g.LogNextPrefix;
13573
0
    const char* suffix = g.LogNextSuffix;
13574
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13575
13576
0
    if (!text_end)
13577
0
        text_end = FindRenderedTextEnd(text, text_end);
13578
13579
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13580
0
    if (ref_pos)
13581
0
        g.LogLinePosY = ref_pos->y;
13582
0
    if (log_new_line)
13583
0
    {
13584
0
        LogText(IM_NEWLINE);
13585
0
        g.LogLineFirstItem = true;
13586
0
    }
13587
13588
0
    if (prefix)
13589
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13590
13591
    // Re-adjust padding if we have popped out of our starting depth
13592
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13593
0
        g.LogDepthRef = window->DC.TreeDepth;
13594
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13595
13596
0
    const char* text_remaining = text;
13597
0
    for (;;)
13598
0
    {
13599
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13600
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13601
0
        const char* line_start = text_remaining;
13602
0
        const char* line_end = ImStreolRange(line_start, text_end);
13603
0
        const bool is_last_line = (line_end == text_end);
13604
0
        if (line_start != line_end || !is_last_line)
13605
0
        {
13606
0
            const int line_length = (int)(line_end - line_start);
13607
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13608
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13609
0
            g.LogLineFirstItem = false;
13610
0
            if (*line_end == '\n')
13611
0
            {
13612
0
                LogText(IM_NEWLINE);
13613
0
                g.LogLineFirstItem = true;
13614
0
            }
13615
0
        }
13616
0
        if (is_last_line)
13617
0
            break;
13618
0
        text_remaining = line_end + 1;
13619
0
    }
13620
13621
0
    if (suffix)
13622
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13623
0
}
13624
13625
// Start logging/capturing text output
13626
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13627
0
{
13628
0
    ImGuiContext& g = *GImGui;
13629
0
    ImGuiWindow* window = g.CurrentWindow;
13630
0
    IM_ASSERT(g.LogEnabled == false);
13631
0
    IM_ASSERT(g.LogFile == NULL);
13632
0
    IM_ASSERT(g.LogBuffer.empty());
13633
0
    g.LogEnabled = true;
13634
0
    g.LogType = type;
13635
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13636
0
    g.LogDepthRef = window->DC.TreeDepth;
13637
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13638
0
    g.LogLinePosY = FLT_MAX;
13639
0
    g.LogLineFirstItem = true;
13640
0
}
13641
13642
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13643
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13644
0
{
13645
0
    ImGuiContext& g = *GImGui;
13646
0
    g.LogNextPrefix = prefix;
13647
0
    g.LogNextSuffix = suffix;
13648
0
}
13649
13650
void ImGui::LogToTTY(int auto_open_depth)
13651
0
{
13652
0
    ImGuiContext& g = *GImGui;
13653
0
    if (g.LogEnabled)
13654
0
        return;
13655
0
    IM_UNUSED(auto_open_depth);
13656
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13657
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13658
0
    g.LogFile = stdout;
13659
0
#endif
13660
0
}
13661
13662
// Start logging/capturing text output to given file
13663
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13664
0
{
13665
0
    ImGuiContext& g = *GImGui;
13666
0
    if (g.LogEnabled)
13667
0
        return;
13668
13669
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13670
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13671
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13672
0
    if (!filename)
13673
0
        filename = g.IO.LogFilename;
13674
0
    if (!filename || !filename[0])
13675
0
        return;
13676
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13677
0
    if (!f)
13678
0
    {
13679
0
        IM_ASSERT(0);
13680
0
        return;
13681
0
    }
13682
13683
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13684
0
    g.LogFile = f;
13685
0
}
13686
13687
// Start logging/capturing text output to clipboard
13688
void ImGui::LogToClipboard(int auto_open_depth)
13689
0
{
13690
0
    ImGuiContext& g = *GImGui;
13691
0
    if (g.LogEnabled)
13692
0
        return;
13693
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13694
0
}
13695
13696
void ImGui::LogToBuffer(int auto_open_depth)
13697
0
{
13698
0
    ImGuiContext& g = *GImGui;
13699
0
    if (g.LogEnabled)
13700
0
        return;
13701
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13702
0
}
13703
13704
void ImGui::LogFinish()
13705
48.2k
{
13706
48.2k
    ImGuiContext& g = *GImGui;
13707
48.2k
    if (!g.LogEnabled)
13708
48.2k
        return;
13709
13710
0
    LogText(IM_NEWLINE);
13711
0
    switch (g.LogType)
13712
0
    {
13713
0
    case ImGuiLogType_TTY:
13714
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13715
0
        fflush(g.LogFile);
13716
0
#endif
13717
0
        break;
13718
0
    case ImGuiLogType_File:
13719
0
        ImFileClose(g.LogFile);
13720
0
        break;
13721
0
    case ImGuiLogType_Buffer:
13722
0
        break;
13723
0
    case ImGuiLogType_Clipboard:
13724
0
        if (!g.LogBuffer.empty())
13725
0
            SetClipboardText(g.LogBuffer.begin());
13726
0
        break;
13727
0
    case ImGuiLogType_None:
13728
0
        IM_ASSERT(0);
13729
0
        break;
13730
0
    }
13731
13732
0
    g.LogEnabled = false;
13733
0
    g.LogType = ImGuiLogType_None;
13734
0
    g.LogFile = NULL;
13735
0
    g.LogBuffer.clear();
13736
0
}
13737
13738
// Helper to display logging buttons
13739
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13740
void ImGui::LogButtons()
13741
0
{
13742
0
    ImGuiContext& g = *GImGui;
13743
13744
0
    PushID("LogButtons");
13745
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13746
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13747
#else
13748
    const bool log_to_tty = false;
13749
#endif
13750
0
    const bool log_to_file = Button("Log To File"); SameLine();
13751
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13752
0
    PushTabStop(false);
13753
0
    SetNextItemWidth(80.0f);
13754
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13755
0
    PopTabStop();
13756
0
    PopID();
13757
13758
    // Start logging at the end of the function so that the buttons don't appear in the log
13759
0
    if (log_to_tty)
13760
0
        LogToTTY();
13761
0
    if (log_to_file)
13762
0
        LogToFile();
13763
0
    if (log_to_clipboard)
13764
0
        LogToClipboard();
13765
0
}
13766
13767
13768
//-----------------------------------------------------------------------------
13769
// [SECTION] SETTINGS
13770
//-----------------------------------------------------------------------------
13771
// - UpdateSettings() [Internal]
13772
// - MarkIniSettingsDirty() [Internal]
13773
// - FindSettingsHandler() [Internal]
13774
// - ClearIniSettings() [Internal]
13775
// - LoadIniSettingsFromDisk()
13776
// - LoadIniSettingsFromMemory()
13777
// - SaveIniSettingsToDisk()
13778
// - SaveIniSettingsToMemory()
13779
//-----------------------------------------------------------------------------
13780
// - CreateNewWindowSettings() [Internal]
13781
// - FindWindowSettingsByID() [Internal]
13782
// - FindWindowSettingsByWindow() [Internal]
13783
// - ClearWindowSettings() [Internal]
13784
// - WindowSettingsHandler_***() [Internal]
13785
//-----------------------------------------------------------------------------
13786
13787
// Called by NewFrame()
13788
void ImGui::UpdateSettings()
13789
24.1k
{
13790
    // Load settings on first frame (if not explicitly loaded manually before)
13791
24.1k
    ImGuiContext& g = *GImGui;
13792
24.1k
    if (!g.SettingsLoaded)
13793
1
    {
13794
1
        IM_ASSERT(g.SettingsWindows.empty());
13795
1
        if (g.IO.IniFilename)
13796
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13797
1
        g.SettingsLoaded = true;
13798
1
    }
13799
13800
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13801
24.1k
    if (g.SettingsDirtyTimer > 0.0f)
13802
1.20k
    {
13803
1.20k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13804
1.20k
        if (g.SettingsDirtyTimer <= 0.0f)
13805
4
        {
13806
4
            if (g.IO.IniFilename != NULL)
13807
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13808
4
            else
13809
4
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13810
4
            g.SettingsDirtyTimer = 0.0f;
13811
4
        }
13812
1.20k
    }
13813
24.1k
}
13814
13815
void ImGui::MarkIniSettingsDirty()
13816
0
{
13817
0
    ImGuiContext& g = *GImGui;
13818
0
    if (g.SettingsDirtyTimer <= 0.0f)
13819
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13820
0
}
13821
13822
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13823
4.68k
{
13824
4.68k
    ImGuiContext& g = *GImGui;
13825
4.68k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13826
6
        if (g.SettingsDirtyTimer <= 0.0f)
13827
4
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13828
4.68k
}
13829
13830
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13831
2
{
13832
2
    ImGuiContext& g = *GImGui;
13833
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13834
2
    g.SettingsHandlers.push_back(*handler);
13835
2
}
13836
13837
void ImGui::RemoveSettingsHandler(const char* type_name)
13838
0
{
13839
0
    ImGuiContext& g = *GImGui;
13840
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13841
0
        g.SettingsHandlers.erase(handler);
13842
0
}
13843
13844
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13845
2
{
13846
2
    ImGuiContext& g = *GImGui;
13847
2
    const ImGuiID type_hash = ImHashStr(type_name);
13848
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13849
1
        if (handler.TypeHash == type_hash)
13850
0
            return &handler;
13851
2
    return NULL;
13852
2
}
13853
13854
// Clear all settings (windows, tables, docking etc.)
13855
void ImGui::ClearIniSettings()
13856
0
{
13857
0
    ImGuiContext& g = *GImGui;
13858
0
    g.SettingsIniData.clear();
13859
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13860
0
        if (handler.ClearAllFn != NULL)
13861
0
            handler.ClearAllFn(&g, &handler);
13862
0
}
13863
13864
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13865
0
{
13866
0
    size_t file_data_size = 0;
13867
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13868
0
    if (!file_data)
13869
0
        return;
13870
0
    if (file_data_size > 0)
13871
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13872
0
    IM_FREE(file_data);
13873
0
}
13874
13875
// Zero-tolerance, no error reporting, cheap .ini parsing
13876
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13877
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13878
0
{
13879
0
    ImGuiContext& g = *GImGui;
13880
0
    IM_ASSERT(g.Initialized);
13881
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13882
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13883
13884
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13885
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13886
0
    if (ini_size == 0)
13887
0
        ini_size = strlen(ini_data);
13888
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13889
0
    char* const buf = g.SettingsIniData.Buf.Data;
13890
0
    char* const buf_end = buf + ini_size;
13891
0
    memcpy(buf, ini_data, ini_size);
13892
0
    buf_end[0] = 0;
13893
13894
    // Call pre-read handlers
13895
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13896
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13897
0
        if (handler.ReadInitFn != NULL)
13898
0
            handler.ReadInitFn(&g, &handler);
13899
13900
0
    void* entry_data = NULL;
13901
0
    ImGuiSettingsHandler* entry_handler = NULL;
13902
13903
0
    char* line_end = NULL;
13904
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13905
0
    {
13906
        // Skip new lines markers, then find end of the line
13907
0
        while (*line == '\n' || *line == '\r')
13908
0
            line++;
13909
0
        line_end = line;
13910
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13911
0
            line_end++;
13912
0
        line_end[0] = 0;
13913
0
        if (line[0] == ';')
13914
0
            continue;
13915
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13916
0
        {
13917
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13918
0
            line_end[-1] = 0;
13919
0
            const char* name_end = line_end - 1;
13920
0
            const char* type_start = line + 1;
13921
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13922
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13923
0
            if (!type_end || !name_start)
13924
0
                continue;
13925
0
            *type_end = 0; // Overwrite first ']'
13926
0
            name_start++;  // Skip second '['
13927
0
            entry_handler = FindSettingsHandler(type_start);
13928
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13929
0
        }
13930
0
        else if (entry_handler != NULL && entry_data != NULL)
13931
0
        {
13932
            // Let type handler parse the line
13933
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13934
0
        }
13935
0
    }
13936
0
    g.SettingsLoaded = true;
13937
13938
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13939
0
    memcpy(buf, ini_data, ini_size);
13940
13941
    // Call post-read handlers
13942
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13943
0
        if (handler.ApplyAllFn != NULL)
13944
0
            handler.ApplyAllFn(&g, &handler);
13945
0
}
13946
13947
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13948
0
{
13949
0
    ImGuiContext& g = *GImGui;
13950
0
    g.SettingsDirtyTimer = 0.0f;
13951
0
    if (!ini_filename)
13952
0
        return;
13953
13954
0
    size_t ini_data_size = 0;
13955
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13956
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13957
0
    if (!f)
13958
0
        return;
13959
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13960
0
    ImFileClose(f);
13961
0
}
13962
13963
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13964
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13965
0
{
13966
0
    ImGuiContext& g = *GImGui;
13967
0
    g.SettingsDirtyTimer = 0.0f;
13968
0
    g.SettingsIniData.Buf.resize(0);
13969
0
    g.SettingsIniData.Buf.push_back(0);
13970
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13971
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
13972
0
    if (out_size)
13973
0
        *out_size = (size_t)g.SettingsIniData.size();
13974
0
    return g.SettingsIniData.c_str();
13975
0
}
13976
13977
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13978
0
{
13979
0
    ImGuiContext& g = *GImGui;
13980
13981
0
    if (g.IO.ConfigDebugIniSettings == false)
13982
0
    {
13983
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13984
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
13985
0
        if (const char* p = strstr(name, "###"))
13986
0
            name = p;
13987
0
    }
13988
0
    const size_t name_len = strlen(name);
13989
13990
    // Allocate chunk
13991
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13992
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13993
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13994
0
    settings->ID = ImHashStr(name, name_len);
13995
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13996
13997
0
    return settings;
13998
0
}
13999
14000
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14001
// This is called once per window .ini entry + once per newly instantiated window.
14002
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14003
2
{
14004
2
    ImGuiContext& g = *GImGui;
14005
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14006
0
        if (settings->ID == id && !settings->WantDelete)
14007
0
            return settings;
14008
2
    return NULL;
14009
2
}
14010
14011
// This is faster if you are holding on a Window already as we don't need to perform a search.
14012
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14013
2
{
14014
2
    ImGuiContext& g = *GImGui;
14015
2
    if (window->SettingsOffset != -1)
14016
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14017
2
    return FindWindowSettingsByID(window->ID);
14018
2
}
14019
14020
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14021
void ImGui::ClearWindowSettings(const char* name)
14022
0
{
14023
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14024
0
    ImGuiContext& g = *GImGui;
14025
0
    ImGuiWindow* window = FindWindowByName(name);
14026
0
    if (window != NULL)
14027
0
    {
14028
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14029
0
        InitOrLoadWindowSettings(window, NULL);
14030
0
        if (window->DockId != 0)
14031
0
            DockContextProcessUndockWindow(&g, window, true);
14032
0
    }
14033
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14034
0
        settings->WantDelete = true;
14035
0
}
14036
14037
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14038
0
{
14039
0
    ImGuiContext& g = *ctx;
14040
0
    for (ImGuiWindow* window : g.Windows)
14041
0
        window->SettingsOffset = -1;
14042
0
    g.SettingsWindows.clear();
14043
0
}
14044
14045
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14046
0
{
14047
0
    ImGuiID id = ImHashStr(name);
14048
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14049
0
    if (settings)
14050
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14051
0
    else
14052
0
        settings = ImGui::CreateNewWindowSettings(name);
14053
0
    settings->ID = id;
14054
0
    settings->WantApply = true;
14055
0
    return (void*)settings;
14056
0
}
14057
14058
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14059
0
{
14060
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14061
0
    int x, y;
14062
0
    int i;
14063
0
    ImU32 u1;
14064
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14065
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14066
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14067
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14068
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14069
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14070
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14071
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14072
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14073
0
}
14074
14075
// Apply to existing windows (if any)
14076
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14077
0
{
14078
0
    ImGuiContext& g = *ctx;
14079
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14080
0
        if (settings->WantApply)
14081
0
        {
14082
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14083
0
                ApplyWindowSettings(window, settings);
14084
0
            settings->WantApply = false;
14085
0
        }
14086
0
}
14087
14088
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14089
0
{
14090
    // Gather data from windows that were active during this session
14091
    // (if a window wasn't opened in this session we preserve its settings)
14092
0
    ImGuiContext& g = *ctx;
14093
0
    for (ImGuiWindow* window : g.Windows)
14094
0
    {
14095
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14096
0
            continue;
14097
14098
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14099
0
        if (!settings)
14100
0
        {
14101
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14102
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14103
0
        }
14104
0
        IM_ASSERT(settings->ID == window->ID);
14105
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14106
0
        settings->Size = ImVec2ih(window->SizeFull);
14107
0
        settings->ViewportId = window->ViewportId;
14108
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14109
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14110
0
        settings->DockId = window->DockId;
14111
0
        settings->ClassId = window->WindowClass.ClassId;
14112
0
        settings->DockOrder = window->DockOrder;
14113
0
        settings->Collapsed = window->Collapsed;
14114
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14115
0
        settings->WantDelete = false;
14116
0
    }
14117
14118
    // Write to text buffer
14119
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14120
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14121
0
    {
14122
0
        if (settings->WantDelete)
14123
0
            continue;
14124
0
        const char* settings_name = settings->GetName();
14125
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14126
0
        if (settings->IsChild)
14127
0
        {
14128
0
            buf->appendf("IsChild=1\n");
14129
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14130
0
        }
14131
0
        else
14132
0
        {
14133
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14134
0
            {
14135
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14136
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14137
0
            }
14138
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14139
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14140
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14141
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14142
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14143
0
            if (settings->DockId != 0)
14144
0
            {
14145
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14146
0
                if (settings->DockOrder == -1)
14147
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14148
0
                else
14149
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14150
0
                if (settings->ClassId != 0)
14151
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14152
0
            }
14153
0
        }
14154
0
        buf->append("\n");
14155
0
    }
14156
0
}
14157
14158
14159
//-----------------------------------------------------------------------------
14160
// [SECTION] LOCALIZATION
14161
//-----------------------------------------------------------------------------
14162
14163
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14164
1
{
14165
1
    ImGuiContext& g = *GImGui;
14166
12
    for (int n = 0; n < count; n++)
14167
11
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14168
1
}
14169
14170
14171
//-----------------------------------------------------------------------------
14172
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14173
//-----------------------------------------------------------------------------
14174
// - GetMainViewport()
14175
// - FindViewportByID()
14176
// - FindViewportByPlatformHandle()
14177
// - SetCurrentViewport() [Internal]
14178
// - SetWindowViewport() [Internal]
14179
// - GetWindowAlwaysWantOwnViewport() [Internal]
14180
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14181
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14182
// - TranslateWindowsInViewport() [Internal]
14183
// - ScaleWindowsInViewport() [Internal]
14184
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14185
// - UpdateViewportsNewFrame() [Internal]
14186
// - UpdateViewportsEndFrame() [Internal]
14187
// - AddUpdateViewport() [Internal]
14188
// - WindowSelectViewport() [Internal]
14189
// - WindowSyncOwnedViewport() [Internal]
14190
// - UpdatePlatformWindows()
14191
// - RenderPlatformWindowsDefault()
14192
// - FindPlatformMonitorForPos() [Internal]
14193
// - FindPlatformMonitorForRect() [Internal]
14194
// - UpdateViewportPlatformMonitor() [Internal]
14195
// - DestroyPlatformWindow() [Internal]
14196
// - DestroyPlatformWindows()
14197
//-----------------------------------------------------------------------------
14198
14199
ImGuiViewport* ImGui::GetMainViewport()
14200
71.8k
{
14201
71.8k
    ImGuiContext& g = *GImGui;
14202
71.8k
    return g.Viewports[0];
14203
71.8k
}
14204
14205
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14206
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14207
24.1k
{
14208
24.1k
    ImGuiContext& g = *GImGui;
14209
24.1k
    for (ImGuiViewportP* viewport : g.Viewports)
14210
24.1k
        if (viewport->ID == id)
14211
24.1k
            return viewport;
14212
0
    return NULL;
14213
24.1k
}
14214
14215
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14216
0
{
14217
0
    ImGuiContext& g = *GImGui;
14218
0
    for (ImGuiViewportP* viewport : g.Viewports)
14219
0
        if (viewport->PlatformHandle == platform_handle)
14220
0
            return viewport;
14221
0
    return NULL;
14222
0
}
14223
14224
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14225
143k
{
14226
143k
    ImGuiContext& g = *GImGui;
14227
143k
    (void)current_window;
14228
14229
143k
    if (viewport)
14230
119k
        viewport->LastFrameActive = g.FrameCount;
14231
143k
    if (g.CurrentViewport == viewport)
14232
95.5k
        return;
14233
48.2k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14234
48.2k
    g.CurrentViewport = viewport;
14235
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14236
14237
    // Notify platform layer of viewport changes
14238
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14239
48.2k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14240
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14241
48.2k
}
14242
14243
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14244
71.8k
{
14245
    // Abandon viewport
14246
71.8k
    if (window->ViewportOwned && window->Viewport->Window == window)
14247
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14248
14249
71.8k
    window->Viewport = viewport;
14250
71.8k
    window->ViewportId = viewport->ID;
14251
71.8k
    window->ViewportOwned = (viewport->Window == window);
14252
71.8k
}
14253
14254
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14255
0
{
14256
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14257
0
    ImGuiContext& g = *GImGui;
14258
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14259
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14260
0
            if (!window->DockIsActive)
14261
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14262
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14263
0
                        return true;
14264
0
    return false;
14265
0
}
14266
14267
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14268
0
{
14269
0
    ImGuiContext& g = *GImGui;
14270
0
    if (window->Viewport == viewport)
14271
0
        return false;
14272
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14273
0
        return false;
14274
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14275
0
        return false;
14276
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14277
0
        return false;
14278
0
    if (GetWindowAlwaysWantOwnViewport(window))
14279
0
        return false;
14280
14281
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14282
0
    for (ImGuiWindow* window_behind : g.Windows)
14283
0
    {
14284
0
        if (window_behind == window)
14285
0
            break;
14286
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14287
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14288
0
                return false;
14289
0
    }
14290
14291
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14292
0
    ImGuiViewportP* old_viewport = window->Viewport;
14293
0
    if (window->ViewportOwned)
14294
0
        for (int n = 0; n < g.Windows.Size; n++)
14295
0
            if (g.Windows[n]->Viewport == old_viewport)
14296
0
                SetWindowViewport(g.Windows[n], viewport);
14297
0
    SetWindowViewport(window, viewport);
14298
0
    BringWindowToDisplayFront(window);
14299
14300
0
    return true;
14301
0
}
14302
14303
// FIXME: handle 0 to N host viewports
14304
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14305
0
{
14306
0
    ImGuiContext& g = *GImGui;
14307
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14308
0
}
14309
14310
// Translate Dear ImGui windows when a Host Viewport has been moved
14311
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14312
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14313
0
{
14314
0
    ImGuiContext& g = *GImGui;
14315
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14316
14317
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14318
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14319
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14320
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14321
    // and so the window will appear to teleport when releasing the mouse.
14322
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14323
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14324
0
    ImVec2 delta_pos = new_pos - old_pos;
14325
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14326
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14327
0
            TranslateWindow(window, delta_pos);
14328
0
}
14329
14330
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14331
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14332
0
{
14333
0
    ImGuiContext& g = *GImGui;
14334
0
    if (viewport->Window)
14335
0
    {
14336
0
        ScaleWindow(viewport->Window, scale);
14337
0
    }
14338
0
    else
14339
0
    {
14340
0
        for (ImGuiWindow* window : g.Windows)
14341
0
            if (window->Viewport == viewport)
14342
0
                ScaleWindow(window, scale);
14343
0
    }
14344
0
}
14345
14346
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14347
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14348
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14349
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14350
0
{
14351
0
    ImGuiContext& g = *GImGui;
14352
0
    ImGuiViewportP* best_candidate = NULL;
14353
0
    for (ImGuiViewportP* viewport : g.Viewports)
14354
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14355
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14356
0
                best_candidate = viewport;
14357
0
    return best_candidate;
14358
0
}
14359
14360
// Update viewports and monitor infos
14361
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14362
static void ImGui::UpdateViewportsNewFrame()
14363
24.1k
{
14364
24.1k
    ImGuiContext& g = *GImGui;
14365
24.1k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14366
14367
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14368
    // Update Focused status
14369
24.1k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14370
24.1k
    if (viewports_enabled)
14371
0
    {
14372
0
        ImGuiViewportP* focused_viewport = NULL;
14373
0
        for (ImGuiViewportP* viewport : g.Viewports)
14374
0
        {
14375
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14376
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14377
0
            {
14378
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14379
0
                if (is_minimized)
14380
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14381
0
                else
14382
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14383
0
            }
14384
14385
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14386
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14387
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14388
0
            {
14389
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14390
0
                if (is_focused)
14391
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14392
0
                else
14393
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14394
0
                if (is_focused)
14395
0
                    focused_viewport = viewport;
14396
0
            }
14397
0
        }
14398
14399
        // Focused viewport has changed?
14400
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14401
0
        {
14402
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14403
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14404
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14405
14406
            // Store a tag so we can infer z-order easily from all our windows
14407
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14408
            // will keep the front most stamp instead of losing it back to their parent viewport.
14409
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14410
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14411
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14412
14413
            // Focus associated dear imgui window
14414
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14415
            // - if focus didn't happen because we destroyed another window (#6462)
14416
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14417
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14418
0
            if (apply_imgui_focus_on_focused_viewport)
14419
0
            {
14420
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14421
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14422
0
                if (focused_viewport->Window != NULL)
14423
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14424
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14425
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14426
0
                else
14427
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14428
0
            }
14429
0
        }
14430
0
        if (focused_viewport)
14431
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14432
0
    }
14433
14434
    // Create/update main viewport with current platform position.
14435
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14436
24.1k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14437
24.1k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14438
24.1k
    IM_ASSERT(main_viewport->Window == NULL);
14439
24.1k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14440
24.1k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14441
24.1k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14442
0
    {
14443
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14444
0
        main_viewport_size = main_viewport->Size;
14445
0
    }
14446
24.1k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14447
14448
24.1k
    g.CurrentDpiScale = 0.0f;
14449
24.1k
    g.CurrentViewport = NULL;
14450
24.1k
    g.MouseViewport = NULL;
14451
48.2k
    for (int n = 0; n < g.Viewports.Size; n++)
14452
24.1k
    {
14453
24.1k
        ImGuiViewportP* viewport = g.Viewports[n];
14454
24.1k
        viewport->Idx = n;
14455
14456
        // Erase unused viewports
14457
24.1k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14458
0
        {
14459
0
            DestroyViewport(viewport);
14460
0
            n--;
14461
0
            continue;
14462
0
        }
14463
14464
24.1k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14465
24.1k
        if (viewports_enabled)
14466
0
        {
14467
            // Update Position and Size (from Platform Window to ImGui) if requested.
14468
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14469
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14470
0
            {
14471
                // Viewport->WorkPos and WorkSize will be updated below
14472
0
                if (viewport->PlatformRequestMove)
14473
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14474
0
                if (viewport->PlatformRequestResize)
14475
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14476
0
            }
14477
0
        }
14478
14479
        // Update/copy monitor info
14480
24.1k
        UpdateViewportPlatformMonitor(viewport);
14481
14482
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14483
24.1k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14484
24.1k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14485
24.1k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14486
24.1k
        viewport->UpdateWorkRect();
14487
14488
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14489
24.1k
        viewport->Alpha = 1.0f;
14490
14491
        // Translate Dear ImGui windows when a Host Viewport has been moved
14492
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14493
24.1k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14494
24.1k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14495
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14496
14497
        // Update DPI scale
14498
24.1k
        float new_dpi_scale;
14499
24.1k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14500
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14501
24.1k
        else if (viewport->PlatformMonitor != -1)
14502
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14503
24.1k
        else
14504
24.1k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14505
24.1k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14506
0
        {
14507
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14508
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14509
0
                ScaleWindowsInViewport(viewport, scale_factor);
14510
            //if (viewport == GetMainViewport())
14511
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14512
14513
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14514
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14515
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14516
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14517
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14518
0
        }
14519
24.1k
        viewport->DpiScale = new_dpi_scale;
14520
24.1k
    }
14521
14522
    // Update fallback monitor
14523
24.1k
    if (g.PlatformIO.Monitors.Size == 0)
14524
24.1k
    {
14525
24.1k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14526
24.1k
        monitor->MainPos = main_viewport->Pos;
14527
24.1k
        monitor->MainSize = main_viewport->Size;
14528
24.1k
        monitor->WorkPos = main_viewport->WorkPos;
14529
24.1k
        monitor->WorkSize = main_viewport->WorkSize;
14530
24.1k
        monitor->DpiScale = main_viewport->DpiScale;
14531
24.1k
    }
14532
14533
24.1k
    if (!viewports_enabled)
14534
24.1k
    {
14535
24.1k
        g.MouseViewport = main_viewport;
14536
24.1k
        return;
14537
24.1k
    }
14538
14539
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14540
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14541
0
    ImGuiViewportP* viewport_hovered = NULL;
14542
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14543
0
    {
14544
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14545
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14546
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14547
0
    }
14548
0
    else
14549
0
    {
14550
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14551
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14552
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14553
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14554
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14555
0
    }
14556
0
    if (viewport_hovered != NULL)
14557
0
        g.MouseLastHoveredViewport = viewport_hovered;
14558
0
    else if (g.MouseLastHoveredViewport == NULL)
14559
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14560
14561
    // Update mouse reference viewport
14562
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14563
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14564
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14565
0
        g.MouseViewport = g.MovingWindow->Viewport;
14566
0
    else
14567
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14568
14569
    // When dragging something, always refer to the last hovered viewport.
14570
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14571
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14572
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14573
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14574
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14575
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14576
0
        viewport_hovered = g.MouseLastHoveredViewport;
14577
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14578
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14579
0
            g.MouseViewport = viewport_hovered;
14580
14581
0
    IM_ASSERT(g.MouseViewport != NULL);
14582
0
}
14583
14584
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14585
static void ImGui::UpdateViewportsEndFrame()
14586
24.1k
{
14587
24.1k
    ImGuiContext& g = *GImGui;
14588
24.1k
    g.PlatformIO.Viewports.resize(0);
14589
48.2k
    for (int i = 0; i < g.Viewports.Size; i++)
14590
24.1k
    {
14591
24.1k
        ImGuiViewportP* viewport = g.Viewports[i];
14592
24.1k
        viewport->LastPos = viewport->Pos;
14593
24.1k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14594
0
            if (i > 0) // Always include main viewport in the list
14595
0
                continue;
14596
24.1k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14597
0
            continue;
14598
24.1k
        if (i > 0)
14599
24.1k
            IM_ASSERT(viewport->Window != NULL);
14600
24.1k
        g.PlatformIO.Viewports.push_back(viewport);
14601
24.1k
    }
14602
24.1k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14603
24.1k
}
14604
14605
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14606
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14607
24.1k
{
14608
24.1k
    ImGuiContext& g = *GImGui;
14609
24.1k
    IM_ASSERT(id != 0);
14610
14611
24.1k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14612
24.1k
    if (window != NULL)
14613
0
    {
14614
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14615
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14616
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14617
0
            flags |= ImGuiViewportFlags_NoInputs;
14618
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14619
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14620
0
    }
14621
14622
24.1k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14623
24.1k
    if (viewport)
14624
24.1k
    {
14625
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14626
24.1k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14627
24.1k
            viewport->Pos = pos;
14628
24.1k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14629
24.1k
            viewport->Size = size;
14630
24.1k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14631
24.1k
    }
14632
0
    else
14633
0
    {
14634
        // New viewport
14635
0
        viewport = IM_NEW(ImGuiViewportP)();
14636
0
        viewport->ID = id;
14637
0
        viewport->Idx = g.Viewports.Size;
14638
0
        viewport->Pos = viewport->LastPos = pos;
14639
0
        viewport->Size = size;
14640
0
        viewport->Flags = flags;
14641
0
        UpdateViewportPlatformMonitor(viewport);
14642
0
        g.Viewports.push_back(viewport);
14643
0
        g.ViewportCreatedCount++;
14644
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14645
14646
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14647
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14648
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14649
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14650
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14651
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14652
14653
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14654
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14655
0
        if (viewport->PlatformMonitor != -1)
14656
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14657
0
    }
14658
14659
24.1k
    viewport->Window = window;
14660
24.1k
    viewport->LastFrameActive = g.FrameCount;
14661
24.1k
    viewport->UpdateWorkRect();
14662
24.1k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14663
14664
24.1k
    if (window != NULL)
14665
0
        window->ViewportOwned = true;
14666
14667
24.1k
    return viewport;
14668
24.1k
}
14669
14670
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14671
0
{
14672
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14673
0
    ImGuiContext& g = *GImGui;
14674
0
    for (ImGuiWindow* window : g.Windows)
14675
0
    {
14676
0
        if (window->Viewport != viewport)
14677
0
            continue;
14678
0
        window->Viewport = NULL;
14679
0
        window->ViewportOwned = false;
14680
0
    }
14681
0
    if (viewport == g.MouseLastHoveredViewport)
14682
0
        g.MouseLastHoveredViewport = NULL;
14683
14684
    // Destroy
14685
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14686
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14687
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14688
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14689
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14690
0
    IM_DELETE(viewport);
14691
0
}
14692
14693
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14694
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14695
71.8k
{
14696
71.8k
    ImGuiContext& g = *GImGui;
14697
71.8k
    ImGuiWindowFlags flags = window->Flags;
14698
71.8k
    window->ViewportAllowPlatformMonitorExtend = -1;
14699
14700
    // Restore main viewport if multi-viewport is not supported by the backend
14701
71.8k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14702
71.8k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14703
71.8k
    {
14704
71.8k
        SetWindowViewport(window, main_viewport);
14705
71.8k
        return;
14706
71.8k
    }
14707
0
    window->ViewportOwned = false;
14708
14709
    // Appearing popups reset their viewport so they can inherit again
14710
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14711
0
    {
14712
0
        window->Viewport = NULL;
14713
0
        window->ViewportId = 0;
14714
0
    }
14715
14716
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14717
0
    {
14718
        // By default inherit from parent window
14719
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14720
0
            window->Viewport = window->ParentWindow->Viewport;
14721
14722
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14723
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14724
0
        {
14725
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14726
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14727
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14728
0
        }
14729
0
    }
14730
14731
0
    bool lock_viewport = false;
14732
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14733
0
    {
14734
        // Code explicitly request a viewport
14735
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14736
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14737
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
14738
0
        {
14739
0
            window->Viewport->Window = window;
14740
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
14741
0
        }
14742
0
        lock_viewport = true;
14743
0
    }
14744
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14745
0
    {
14746
        // Always inherit viewport from parent window
14747
0
        if (window->DockNode && window->DockNode->HostWindow)
14748
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14749
0
        window->Viewport = window->ParentWindow->Viewport;
14750
0
    }
14751
0
    else if (window->DockNode && window->DockNode->HostWindow)
14752
0
    {
14753
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14754
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14755
0
    }
14756
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14757
0
    {
14758
0
        window->Viewport = g.MouseViewport;
14759
0
    }
14760
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14761
0
    {
14762
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14763
0
    }
14764
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14765
0
    {
14766
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14767
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14768
0
    }
14769
0
    else
14770
0
    {
14771
        // Merge into host viewport?
14772
        // We cannot test window->ViewportOwned as it set lower in the function.
14773
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14774
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14775
0
        if (try_to_merge_into_host_viewport)
14776
0
            UpdateTryMergeWindowIntoHostViewports(window);
14777
0
    }
14778
14779
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14780
0
    if (window->Viewport == NULL)
14781
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14782
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14783
14784
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14785
0
    if (!lock_viewport)
14786
0
    {
14787
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14788
0
        {
14789
            // We need to take account of the possibility that mouse may become invalid.
14790
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14791
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14792
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14793
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14794
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14795
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14796
0
            else
14797
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14798
0
        }
14799
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14800
0
        {
14801
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14802
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14803
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14804
0
            {
14805
                // Steal/transfer ownership
14806
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14807
0
                window->Viewport->Window = window;
14808
0
                window->Viewport->ID = window->ID;
14809
0
                window->Viewport->LastNameHash = 0;
14810
0
            }
14811
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14812
0
            {
14813
                // New viewport
14814
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14815
0
            }
14816
0
        }
14817
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14818
0
        {
14819
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14820
            // Child windows are kept contained within their parent.
14821
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14822
0
        }
14823
0
    }
14824
14825
    // Update flags
14826
0
    window->ViewportOwned = (window == window->Viewport->Window);
14827
0
    window->ViewportId = window->Viewport->ID;
14828
14829
    // If the OS window has a title bar, hide our imgui title bar
14830
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14831
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14832
0
}
14833
14834
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14835
0
{
14836
0
    ImGuiContext& g = *GImGui;
14837
14838
0
    bool viewport_rect_changed = false;
14839
14840
    // Synchronize window --> viewport in most situations
14841
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14842
0
    if (window->Viewport->PlatformRequestMove)
14843
0
    {
14844
0
        window->Pos = window->Viewport->Pos;
14845
0
        MarkIniSettingsDirty(window);
14846
0
    }
14847
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14848
0
    {
14849
0
        viewport_rect_changed = true;
14850
0
        window->Viewport->Pos = window->Pos;
14851
0
    }
14852
14853
0
    if (window->Viewport->PlatformRequestResize)
14854
0
    {
14855
0
        window->Size = window->SizeFull = window->Viewport->Size;
14856
0
        MarkIniSettingsDirty(window);
14857
0
    }
14858
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14859
0
    {
14860
0
        viewport_rect_changed = true;
14861
0
        window->Viewport->Size = window->Size;
14862
0
    }
14863
0
    window->Viewport->UpdateWorkRect();
14864
14865
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14866
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14867
0
    if (viewport_rect_changed)
14868
0
        UpdateViewportPlatformMonitor(window->Viewport);
14869
14870
    // Update common viewport flags
14871
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14872
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14873
0
    ImGuiWindowFlags window_flags = window->Flags;
14874
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14875
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14876
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14877
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14878
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14879
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14880
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14881
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14882
14883
    // Not correct to set modal as topmost because:
14884
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14885
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14886
    //if (flags & ImGuiWindowFlags_Modal)
14887
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14888
14889
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14890
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14891
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14892
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14893
0
    if (is_short_lived_floating_window && !is_modal)
14894
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14895
14896
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14897
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14898
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14899
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14900
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14901
14902
    // We can also tell the backend that clearing the platform window won't be necessary,
14903
    // as our window background is filling the viewport and we have disabled BgAlpha.
14904
    // FIXME: Work on support for per-viewport transparency (#2766)
14905
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14906
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14907
14908
0
    window->Viewport->Flags = viewport_flags;
14909
14910
    // Update parent viewport ID
14911
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14912
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14913
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14914
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14915
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14916
0
    else
14917
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14918
0
}
14919
14920
// Called by user at the end of the main loop, after EndFrame()
14921
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14922
void ImGui::UpdatePlatformWindows()
14923
0
{
14924
0
    ImGuiContext& g = *GImGui;
14925
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14926
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14927
0
    g.FrameCountPlatformEnded = g.FrameCount;
14928
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14929
0
        return;
14930
14931
    // Create/resize/destroy platform windows to match each active viewport.
14932
    // Skip the main viewport (index 0), which is always fully handled by the application!
14933
0
    for (int i = 1; i < g.Viewports.Size; i++)
14934
0
    {
14935
0
        ImGuiViewportP* viewport = g.Viewports[i];
14936
14937
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14938
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14939
0
        bool destroy_platform_window = false;
14940
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14941
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14942
0
        if (destroy_platform_window)
14943
0
        {
14944
0
            DestroyPlatformWindow(viewport);
14945
0
            continue;
14946
0
        }
14947
14948
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14949
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14950
0
            continue;
14951
14952
        // Create window
14953
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14954
0
        if (is_new_platform_window)
14955
0
        {
14956
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14957
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14958
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14959
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14960
0
            g.PlatformWindowsCreatedCount++;
14961
0
            viewport->LastNameHash = 0;
14962
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14963
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14964
0
            viewport->PlatformWindowCreated = true;
14965
0
        }
14966
14967
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14968
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14969
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14970
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14971
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14972
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14973
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14974
0
        viewport->LastPlatformPos = viewport->Pos;
14975
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14976
14977
        // Update title bar (if it changed)
14978
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14979
0
        {
14980
0
            const char* title_begin = window_for_title->Name;
14981
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14982
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14983
0
            if (viewport->LastNameHash != title_hash)
14984
0
            {
14985
0
                char title_end_backup_c = *title_end;
14986
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14987
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14988
0
                *title_end = title_end_backup_c;
14989
0
                viewport->LastNameHash = title_hash;
14990
0
            }
14991
0
        }
14992
14993
        // Update alpha (if it changed)
14994
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14995
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14996
0
        viewport->LastAlpha = viewport->Alpha;
14997
14998
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14999
0
        if (g.PlatformIO.Platform_UpdateWindow)
15000
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15001
15002
0
        if (is_new_platform_window)
15003
0
        {
15004
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15005
0
            if (g.FrameCount < 3)
15006
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15007
15008
            // Show window
15009
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15010
15011
            // Even without focus, we assume the window becomes front-most.
15012
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15013
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15014
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15015
0
        }
15016
15017
        // Clear request flags
15018
0
        viewport->ClearRequestFlags();
15019
0
    }
15020
0
}
15021
15022
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15023
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15024
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15025
//
15026
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15027
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15028
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15029
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15030
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15031
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15032
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15033
//
15034
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15035
0
{
15036
    // Skip the main viewport (index 0), which is always fully handled by the application!
15037
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15038
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15039
0
    {
15040
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15041
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15042
0
            continue;
15043
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15044
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15045
0
    }
15046
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15047
0
    {
15048
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15049
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15050
0
            continue;
15051
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15052
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15053
0
    }
15054
0
}
15055
15056
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15057
0
{
15058
0
    ImGuiContext& g = *GImGui;
15059
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15060
0
    {
15061
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15062
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15063
0
            return monitor_n;
15064
0
    }
15065
0
    return -1;
15066
0
}
15067
15068
// Search for the monitor with the largest intersection area with the given rectangle
15069
// We generally try to avoid searching loops but the monitor count should be very small here
15070
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15071
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15072
24.1k
{
15073
24.1k
    ImGuiContext& g = *GImGui;
15074
15075
24.1k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15076
24.1k
    if (monitor_count <= 1)
15077
24.1k
        return monitor_count - 1;
15078
15079
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15080
    // This is necessary for tooltips which always resize down to zero at first.
15081
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15082
0
    int best_monitor_n = -1;
15083
0
    float best_monitor_surface = 0.001f;
15084
15085
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15086
0
    {
15087
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15088
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15089
0
        if (monitor_rect.Contains(rect))
15090
0
            return monitor_n;
15091
0
        ImRect overlapping_rect = rect;
15092
0
        overlapping_rect.ClipWithFull(monitor_rect);
15093
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15094
0
        if (overlapping_surface < best_monitor_surface)
15095
0
            continue;
15096
0
        best_monitor_surface = overlapping_surface;
15097
0
        best_monitor_n = monitor_n;
15098
0
    }
15099
0
    return best_monitor_n;
15100
0
}
15101
15102
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15103
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15104
24.1k
{
15105
24.1k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15106
24.1k
}
15107
15108
// Return value is always != NULL, but don't hold on it across frames.
15109
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15110
0
{
15111
0
    ImGuiContext& g = *GImGui;
15112
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15113
0
    int monitor_idx = viewport->PlatformMonitor;
15114
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15115
0
        return &g.PlatformIO.Monitors[monitor_idx];
15116
0
    return &g.FallbackMonitor;
15117
0
}
15118
15119
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15120
0
{
15121
0
    ImGuiContext& g = *GImGui;
15122
0
    if (viewport->PlatformWindowCreated)
15123
0
    {
15124
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15125
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15126
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15127
0
        if (g.PlatformIO.Platform_DestroyWindow)
15128
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15129
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15130
15131
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15132
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15133
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15134
0
            viewport->PlatformWindowCreated = false;
15135
0
    }
15136
0
    else
15137
0
    {
15138
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15139
0
    }
15140
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15141
0
    viewport->ClearRequestFlags();
15142
0
}
15143
15144
void ImGui::DestroyPlatformWindows()
15145
0
{
15146
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15147
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15148
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15149
    // code to operator a consistent manner.
15150
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15151
    // crashing if it doesn't have data stored.
15152
0
    ImGuiContext& g = *GImGui;
15153
0
    for (ImGuiViewportP* viewport : g.Viewports)
15154
0
        DestroyPlatformWindow(viewport);
15155
0
}
15156
15157
15158
//-----------------------------------------------------------------------------
15159
// [SECTION] DOCKING
15160
//-----------------------------------------------------------------------------
15161
// Docking: Internal Types
15162
// Docking: Forward Declarations
15163
// Docking: ImGuiDockContext
15164
// Docking: ImGuiDockContext Docking/Undocking functions
15165
// Docking: ImGuiDockNode
15166
// Docking: ImGuiDockNode Tree manipulation functions
15167
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15168
// Docking: Builder Functions
15169
// Docking: Begin/End Support Functions (called from Begin/End)
15170
// Docking: Settings
15171
//-----------------------------------------------------------------------------
15172
15173
//-----------------------------------------------------------------------------
15174
// Typical Docking call flow: (root level is generally public API):
15175
//-----------------------------------------------------------------------------
15176
// - NewFrame()                               new dear imgui frame
15177
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15178
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15179
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15180
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15181
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15182
//    | - DockContextProcessDock()            - process one docking request
15183
//    | - DockNodeUpdate()
15184
//    |   - DockNodeUpdateForRootNode()
15185
//    |     - DockNodeUpdateFlagsAndCollapse()
15186
//    |     - DockNodeFindInfo()
15187
//    |   - destroy unused node or tab bar
15188
//    |   - create dock node host window
15189
//    |      - Begin() etc.
15190
//    |   - DockNodeStartMouseMovingWindow()
15191
//    |   - DockNodeTreeUpdatePosSize()
15192
//    |   - DockNodeTreeUpdateSplitter()
15193
//    |   - draw node background
15194
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15195
//    |     - DockNodeAddTabBar()
15196
//    |     - DockNodeWindowMenuUpdate()
15197
//    |     - DockNodeCalcTabBarLayout()
15198
//    |     - BeginTabBarEx()
15199
//    |     - TabItemEx() calls
15200
//    |     - EndTabBar()
15201
//    |   - BeginDockableDragDropTarget()
15202
//    |      - DockNodeUpdate()               - recurse into child nodes...
15203
//-----------------------------------------------------------------------------
15204
// - DockSpace()                              user submit a dockspace into a window
15205
//    | Begin(Child)                          - create a child window
15206
//    | DockNodeUpdate()                      - call main dock node update function
15207
//    | End(Child)
15208
//    | ItemSize()
15209
//-----------------------------------------------------------------------------
15210
// - Begin()
15211
//    | BeginDocked()
15212
//    | BeginDockableDragDropSource()
15213
//    | BeginDockableDragDropTarget()
15214
//    | - DockNodePreviewDockRender()
15215
//-----------------------------------------------------------------------------
15216
// - EndFrame()
15217
//    | DockContextEndFrame()
15218
//-----------------------------------------------------------------------------
15219
15220
//-----------------------------------------------------------------------------
15221
// Docking: Internal Types
15222
//-----------------------------------------------------------------------------
15223
// - ImGuiDockRequestType
15224
// - ImGuiDockRequest
15225
// - ImGuiDockPreviewData
15226
// - ImGuiDockNodeSettings
15227
// - ImGuiDockContext
15228
//-----------------------------------------------------------------------------
15229
15230
enum ImGuiDockRequestType
15231
{
15232
    ImGuiDockRequestType_None = 0,
15233
    ImGuiDockRequestType_Dock,
15234
    ImGuiDockRequestType_Undock,
15235
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15236
};
15237
15238
struct ImGuiDockRequest
15239
{
15240
    ImGuiDockRequestType    Type;
15241
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15242
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15243
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15244
    ImGuiDir                DockSplitDir;
15245
    float                   DockSplitRatio;
15246
    bool                    DockSplitOuter;
15247
    ImGuiWindow*            UndockTargetWindow;
15248
    ImGuiDockNode*          UndockTargetNode;
15249
15250
    ImGuiDockRequest()
15251
0
    {
15252
0
        Type = ImGuiDockRequestType_None;
15253
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15254
0
        DockTargetNode = UndockTargetNode = NULL;
15255
0
        DockSplitDir = ImGuiDir_None;
15256
0
        DockSplitRatio = 0.5f;
15257
0
        DockSplitOuter = false;
15258
0
    }
15259
};
15260
15261
struct ImGuiDockPreviewData
15262
{
15263
    ImGuiDockNode   FutureNode;
15264
    bool            IsDropAllowed;
15265
    bool            IsCenterAvailable;
15266
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15267
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15268
    ImGuiDockNode*  SplitNode;
15269
    ImGuiDir        SplitDir;
15270
    float           SplitRatio;
15271
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15272
15273
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15274
};
15275
15276
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15277
struct ImGuiDockNodeSettings
15278
{
15279
    ImGuiID             ID;
15280
    ImGuiID             ParentNodeId;
15281
    ImGuiID             ParentWindowId;
15282
    ImGuiID             SelectedTabId;
15283
    signed char         SplitAxis;
15284
    char                Depth;
15285
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15286
    ImVec2ih            Pos;
15287
    ImVec2ih            Size;
15288
    ImVec2ih            SizeRef;
15289
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15290
};
15291
15292
//-----------------------------------------------------------------------------
15293
// Docking: Forward Declarations
15294
//-----------------------------------------------------------------------------
15295
15296
namespace ImGui
15297
{
15298
    // ImGuiDockContext
15299
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15300
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15301
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15302
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15303
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15304
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15305
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15306
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15307
15308
    // ImGuiDockNode
15309
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15310
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15311
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15312
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15313
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15314
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15315
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15316
    static void             DockNodeUpdate(ImGuiDockNode* node);
15317
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15318
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15319
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15320
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15321
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15322
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15323
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15324
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15325
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15326
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15327
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15328
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15329
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15330
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15331
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15332
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15333
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15334
15335
    // ImGuiDockNode tree manipulations
15336
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15337
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15338
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15339
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15340
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15341
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15342
15343
    // Settings
15344
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15345
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15346
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15347
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15348
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15349
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15350
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15351
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15352
}
15353
15354
//-----------------------------------------------------------------------------
15355
// Docking: ImGuiDockContext
15356
//-----------------------------------------------------------------------------
15357
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15358
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15359
// At boot time only, we run a simple GC to remove nodes that have no references.
15360
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15361
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15362
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15363
//-----------------------------------------------------------------------------
15364
// - DockContextInitialize()
15365
// - DockContextShutdown()
15366
// - DockContextClearNodes()
15367
// - DockContextRebuildNodes()
15368
// - DockContextNewFrameUpdateUndocking()
15369
// - DockContextNewFrameUpdateDocking()
15370
// - DockContextEndFrame()
15371
// - DockContextFindNodeByID()
15372
// - DockContextBindNodeToWindow()
15373
// - DockContextGenNodeID()
15374
// - DockContextAddNode()
15375
// - DockContextRemoveNode()
15376
// - ImGuiDockContextPruneNodeData
15377
// - DockContextPruneUnusedSettingsNodes()
15378
// - DockContextBuildNodesFromSettings()
15379
// - DockContextBuildAddWindowsToNodes()
15380
//-----------------------------------------------------------------------------
15381
15382
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15383
1
{
15384
1
    ImGuiContext& g = *ctx;
15385
15386
    // Add .ini handle for persistent docking data
15387
1
    ImGuiSettingsHandler ini_handler;
15388
1
    ini_handler.TypeName = "Docking";
15389
1
    ini_handler.TypeHash = ImHashStr("Docking");
15390
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15391
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15392
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15393
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15394
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15395
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15396
1
    g.SettingsHandlers.push_back(ini_handler);
15397
15398
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15399
1
}
15400
15401
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15402
0
{
15403
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15404
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15405
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15406
0
            IM_DELETE(node);
15407
0
}
15408
15409
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15410
0
{
15411
0
    IM_UNUSED(ctx);
15412
0
    IM_ASSERT(ctx == GImGui);
15413
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15414
0
    DockBuilderRemoveNodeChildNodes(root_id);
15415
0
}
15416
15417
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15418
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15419
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15420
0
{
15421
0
    ImGuiContext& g = *ctx;
15422
0
    ImGuiDockContext* dc = &ctx->DockContext;
15423
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15424
0
    SaveIniSettingsToMemory();
15425
0
    ImGuiID root_id = 0; // Rebuild all
15426
0
    DockContextClearNodes(ctx, root_id, false);
15427
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15428
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15429
0
}
15430
15431
// Docking context update function, called by NewFrame()
15432
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15433
24.1k
{
15434
24.1k
    ImGuiContext& g = *ctx;
15435
24.1k
    ImGuiDockContext* dc = &ctx->DockContext;
15436
24.1k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15437
0
    {
15438
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15439
0
            DockContextClearNodes(ctx, 0, true);
15440
0
        return;
15441
0
    }
15442
15443
    // Setting NoSplit at runtime merges all nodes
15444
24.1k
    if (g.IO.ConfigDockingNoSplit)
15445
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15446
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15447
0
                if (node->IsRootNode() && node->IsSplitNode())
15448
0
                {
15449
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15450
                    //dc->WantFullRebuild = true;
15451
0
                }
15452
15453
    // Process full rebuild
15454
#if 0
15455
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15456
        dc->WantFullRebuild = true;
15457
#endif
15458
24.1k
    if (dc->WantFullRebuild)
15459
0
    {
15460
0
        DockContextRebuildNodes(ctx);
15461
0
        dc->WantFullRebuild = false;
15462
0
    }
15463
15464
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15465
24.1k
    for (ImGuiDockRequest& req : dc->Requests)
15466
0
    {
15467
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15468
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15469
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15470
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15471
0
    }
15472
24.1k
}
15473
15474
// Docking context update function, called by NewFrame()
15475
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15476
24.1k
{
15477
24.1k
    ImGuiContext& g = *ctx;
15478
24.1k
    ImGuiDockContext* dc  = &ctx->DockContext;
15479
24.1k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15480
0
        return;
15481
15482
    // [DEBUG] Store hovered dock node.
15483
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15484
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15485
24.1k
    g.DebugHoveredDockNode = NULL;
15486
24.1k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15487
851
    {
15488
851
        if (hovered_window->DockNodeAsHost)
15489
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15490
851
        else if (hovered_window->RootWindow->DockNode)
15491
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15492
851
    }
15493
15494
    // Process Docking requests
15495
24.1k
    for (ImGuiDockRequest& req : dc->Requests)
15496
0
        if (req.Type == ImGuiDockRequestType_Dock)
15497
0
            DockContextProcessDock(ctx, &req);
15498
24.1k
    dc->Requests.resize(0);
15499
15500
    // Create windows for each automatic docking nodes
15501
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15502
24.1k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15503
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15504
0
            if (node->IsFloatingNode())
15505
0
                DockNodeUpdate(node);
15506
24.1k
}
15507
15508
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15509
24.1k
{
15510
    // Draw backgrounds of node missing their window
15511
24.1k
    ImGuiContext& g = *ctx;
15512
24.1k
    ImGuiDockContext* dc = &g.DockContext;
15513
24.1k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15514
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15515
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15516
0
            {
15517
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15518
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15519
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15520
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15521
0
            }
15522
24.1k
}
15523
15524
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15525
0
{
15526
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15527
0
}
15528
15529
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15530
0
{
15531
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15532
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15533
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15534
0
    ImGuiID id = 0x0001;
15535
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15536
0
        id++;
15537
0
    return id;
15538
0
}
15539
15540
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15541
0
{
15542
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15543
0
    ImGuiContext& g = *ctx;
15544
0
    if (id == 0)
15545
0
        id = DockContextGenNodeID(ctx);
15546
0
    else
15547
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15548
15549
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15550
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15551
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15552
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15553
0
    return node;
15554
0
}
15555
15556
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15557
0
{
15558
0
    ImGuiContext& g = *ctx;
15559
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15560
15561
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15562
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15563
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15564
0
    IM_ASSERT(node->Windows.Size == 0);
15565
15566
0
    if (node->HostWindow)
15567
0
        node->HostWindow->DockNodeAsHost = NULL;
15568
15569
0
    ImGuiDockNode* parent_node = node->ParentNode;
15570
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15571
0
    if (merge)
15572
0
    {
15573
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15574
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15575
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15576
0
    }
15577
0
    else
15578
0
    {
15579
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15580
0
            if (parent_node->ChildNodes[n] == node)
15581
0
                node->ParentNode->ChildNodes[n] = NULL;
15582
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15583
0
        IM_DELETE(node);
15584
0
    }
15585
0
}
15586
15587
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15588
0
{
15589
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15590
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15591
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15592
0
}
15593
15594
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15595
struct ImGuiDockContextPruneNodeData
15596
{
15597
    int         CountWindows, CountChildWindows, CountChildNodes;
15598
    ImGuiID     RootId;
15599
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15600
};
15601
15602
// Garbage collect unused nodes (run once at init time)
15603
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15604
0
{
15605
0
    ImGuiContext& g = *ctx;
15606
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15607
0
    IM_ASSERT(g.Windows.Size == 0);
15608
15609
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15610
0
    pool.Reserve(dc->NodesSettings.Size);
15611
15612
    // Count child nodes and compute RootID
15613
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15614
0
    {
15615
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15616
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15617
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15618
0
        if (settings->ParentNodeId)
15619
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15620
0
    }
15621
15622
    // Count reference to dock ids from dockspaces
15623
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15624
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15625
0
    {
15626
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15627
0
        if (settings->ParentWindowId != 0)
15628
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15629
0
                if (window_settings->DockId)
15630
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15631
0
                        data->CountChildNodes++;
15632
0
    }
15633
15634
    // Count reference to dock ids from window settings
15635
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15636
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15637
0
        if (ImGuiID dock_id = settings->DockId)
15638
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15639
0
            {
15640
0
                data->CountWindows++;
15641
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15642
0
                    data_root->CountChildWindows++;
15643
0
            }
15644
15645
    // Prune
15646
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15647
0
    {
15648
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15649
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15650
0
        if (data->CountWindows > 1)
15651
0
            continue;
15652
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15653
15654
0
        bool remove = false;
15655
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15656
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15657
0
        remove |= (data_root->CountChildWindows == 0);
15658
0
        if (remove)
15659
0
        {
15660
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15661
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15662
0
            settings->ID = 0;
15663
0
        }
15664
0
    }
15665
0
}
15666
15667
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15668
0
{
15669
    // Build nodes
15670
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15671
0
    {
15672
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15673
0
        if (settings->ID == 0)
15674
0
            continue;
15675
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15676
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15677
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15678
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15679
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15680
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15681
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15682
0
            node->ParentNode->ChildNodes[0] = node;
15683
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15684
0
            node->ParentNode->ChildNodes[1] = node;
15685
0
        node->SelectedTabId = settings->SelectedTabId;
15686
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15687
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15688
15689
        // Bind host window immediately if it already exist (in case of a rebuild)
15690
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15691
0
        char host_window_title[20];
15692
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15693
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15694
0
    }
15695
0
}
15696
15697
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15698
0
{
15699
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15700
0
    ImGuiContext& g = *ctx;
15701
0
    for (ImGuiWindow* window : g.Windows)
15702
0
    {
15703
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15704
0
            continue;
15705
0
        if (window->DockNode != NULL)
15706
0
            continue;
15707
15708
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15709
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15710
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15711
0
            DockNodeAddWindow(node, window, true);
15712
0
    }
15713
0
}
15714
15715
//-----------------------------------------------------------------------------
15716
// Docking: ImGuiDockContext Docking/Undocking functions
15717
//-----------------------------------------------------------------------------
15718
// - DockContextQueueDock()
15719
// - DockContextQueueUndockWindow()
15720
// - DockContextQueueUndockNode()
15721
// - DockContextQueueNotifyRemovedNode()
15722
// - DockContextProcessDock()
15723
// - DockContextProcessUndockWindow()
15724
// - DockContextProcessUndockNode()
15725
// - DockContextCalcDropPosForDocking()
15726
//-----------------------------------------------------------------------------
15727
15728
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15729
0
{
15730
0
    IM_ASSERT(target != payload);
15731
0
    ImGuiDockRequest req;
15732
0
    req.Type = ImGuiDockRequestType_Dock;
15733
0
    req.DockTargetWindow = target;
15734
0
    req.DockTargetNode = target_node;
15735
0
    req.DockPayload = payload;
15736
0
    req.DockSplitDir = split_dir;
15737
0
    req.DockSplitRatio = split_ratio;
15738
0
    req.DockSplitOuter = split_outer;
15739
0
    ctx->DockContext.Requests.push_back(req);
15740
0
}
15741
15742
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15743
0
{
15744
0
    ImGuiDockRequest req;
15745
0
    req.Type = ImGuiDockRequestType_Undock;
15746
0
    req.UndockTargetWindow = window;
15747
0
    ctx->DockContext.Requests.push_back(req);
15748
0
}
15749
15750
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15751
0
{
15752
0
    ImGuiDockRequest req;
15753
0
    req.Type = ImGuiDockRequestType_Undock;
15754
0
    req.UndockTargetNode = node;
15755
0
    ctx->DockContext.Requests.push_back(req);
15756
0
}
15757
15758
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15759
0
{
15760
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15761
0
    for (ImGuiDockRequest& req : dc->Requests)
15762
0
        if (req.DockTargetNode == node)
15763
0
            req.Type = ImGuiDockRequestType_None;
15764
0
}
15765
15766
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15767
0
{
15768
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15769
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15770
15771
0
    ImGuiContext& g = *ctx;
15772
0
    IM_UNUSED(g);
15773
15774
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15775
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15776
0
    ImGuiDockNode* node = req->DockTargetNode;
15777
0
    if (payload_window)
15778
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15779
0
    else
15780
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15781
15782
    // Decide which Tab will be selected at the end of the operation
15783
0
    ImGuiID next_selected_id = 0;
15784
0
    ImGuiDockNode* payload_node = NULL;
15785
0
    if (payload_window)
15786
0
    {
15787
0
        payload_node = payload_window->DockNodeAsHost;
15788
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15789
0
        if (payload_node && payload_node->IsLeafNode())
15790
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15791
0
        if (payload_node == NULL)
15792
0
            next_selected_id = payload_window->TabId;
15793
0
    }
15794
15795
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15796
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15797
0
    if (node)
15798
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15799
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15800
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15801
15802
    // Create new node and add existing window to it
15803
0
    if (node == NULL)
15804
0
    {
15805
0
        node = DockContextAddNode(ctx, 0);
15806
0
        node->Pos = target_window->Pos;
15807
0
        node->Size = target_window->Size;
15808
0
        if (target_window->DockNodeAsHost == NULL)
15809
0
        {
15810
0
            DockNodeAddWindow(node, target_window, true);
15811
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15812
0
            target_window->DockIsActive = true;
15813
0
        }
15814
0
    }
15815
15816
0
    ImGuiDir split_dir = req->DockSplitDir;
15817
0
    if (split_dir != ImGuiDir_None)
15818
0
    {
15819
        // Split into two, one side will be our payload node unless we are dropping a loose window
15820
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15821
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15822
0
        const float split_ratio = req->DockSplitRatio;
15823
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15824
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15825
0
        new_node->HostWindow = node->HostWindow;
15826
0
        node = new_node;
15827
0
    }
15828
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15829
15830
0
    if (node != payload_node)
15831
0
    {
15832
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15833
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15834
0
        {
15835
0
            DockNodeAddTabBar(node);
15836
0
            for (int n = 0; n < node->Windows.Size; n++)
15837
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15838
0
        }
15839
15840
0
        if (payload_node != NULL)
15841
0
        {
15842
            // Transfer full payload node (with 1+ child windows or child nodes)
15843
0
            if (payload_node->IsSplitNode())
15844
0
            {
15845
0
                if (node->Windows.Size > 0)
15846
0
                {
15847
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15848
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15849
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15850
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15851
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15852
0
                    if (visible_node->TabBar)
15853
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15854
0
                    DockNodeMoveWindows(node, visible_node);
15855
0
                    DockNodeMoveWindows(visible_node, node);
15856
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15857
0
                }
15858
0
                if (node->IsCentralNode())
15859
0
                {
15860
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15861
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15862
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15863
0
                    IM_ASSERT(last_focused_node != NULL);
15864
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15865
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15866
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15867
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15868
0
                    last_focused_root_node->CentralNode = last_focused_node;
15869
0
                }
15870
15871
0
                IM_ASSERT(node->Windows.Size == 0);
15872
0
                DockNodeMoveChildNodes(node, payload_node);
15873
0
            }
15874
0
            else
15875
0
            {
15876
0
                const ImGuiID payload_dock_id = payload_node->ID;
15877
0
                DockNodeMoveWindows(node, payload_node);
15878
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15879
0
            }
15880
0
            DockContextRemoveNode(ctx, payload_node, true);
15881
0
        }
15882
0
        else if (payload_window)
15883
0
        {
15884
            // Transfer single window
15885
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15886
0
            node->VisibleWindow = payload_window;
15887
0
            DockNodeAddWindow(node, payload_window, true);
15888
0
            if (payload_dock_id != 0)
15889
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15890
0
        }
15891
0
    }
15892
0
    else
15893
0
    {
15894
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15895
0
        node->WantHiddenTabBarUpdate = true;
15896
0
    }
15897
15898
    // Update selection immediately
15899
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15900
0
        tab_bar->NextSelectedTabId = next_selected_id;
15901
0
    MarkIniSettingsDirty();
15902
0
}
15903
15904
// Problem:
15905
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15906
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15907
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15908
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15909
// Solution:
15910
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15911
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15912
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15913
0
{
15914
0
    if (ref_viewport == NULL)
15915
0
        return size;
15916
15917
0
    ImGuiContext& g = *GImGui;
15918
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
15919
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15920
0
    {
15921
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15922
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
15923
0
    }
15924
0
    return ImMin(size, max_size);
15925
0
}
15926
15927
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15928
0
{
15929
0
    ImGuiContext& g = *ctx;
15930
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15931
0
    if (window->DockNode)
15932
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15933
0
    else
15934
0
        window->DockId = 0;
15935
0
    window->Collapsed = false;
15936
0
    window->DockIsActive = false;
15937
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15938
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15939
15940
0
    MarkIniSettingsDirty();
15941
0
}
15942
15943
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15944
0
{
15945
0
    ImGuiContext& g = *ctx;
15946
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15947
0
    IM_ASSERT(node->IsLeafNode());
15948
0
    IM_ASSERT(node->Windows.Size >= 1);
15949
15950
0
    if (node->IsRootNode() || node->IsCentralNode())
15951
0
    {
15952
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15953
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15954
0
        new_node->Pos = node->Pos;
15955
0
        new_node->Size = node->Size;
15956
0
        new_node->SizeRef = node->SizeRef;
15957
0
        DockNodeMoveWindows(new_node, node);
15958
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15959
0
        node = new_node;
15960
0
    }
15961
0
    else
15962
0
    {
15963
        // Otherwise extract our node and merge our sibling back into the parent node.
15964
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15965
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15966
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15967
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15968
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15969
0
        node->ParentNode = NULL;
15970
0
    }
15971
0
    for (ImGuiWindow* window : node->Windows)
15972
0
    {
15973
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15974
0
        if (window->ParentWindow)
15975
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15976
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15977
0
    }
15978
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15979
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15980
0
    node->WantMouseMove = true;
15981
0
    MarkIniSettingsDirty();
15982
0
}
15983
15984
// This is mostly used for automation.
15985
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15986
0
{
15987
0
    if (target != NULL && target_node == NULL)
15988
0
        target_node = target->DockNode;
15989
15990
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15991
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15992
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15993
0
        split_outer = true;
15994
0
    ImGuiDockPreviewData split_data;
15995
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15996
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15997
0
        return false;
15998
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15999
0
    return true;
16000
0
}
16001
16002
//-----------------------------------------------------------------------------
16003
// Docking: ImGuiDockNode
16004
//-----------------------------------------------------------------------------
16005
// - DockNodeGetTabOrder()
16006
// - DockNodeAddWindow()
16007
// - DockNodeRemoveWindow()
16008
// - DockNodeMoveChildNodes()
16009
// - DockNodeMoveWindows()
16010
// - DockNodeApplyPosSizeToWindows()
16011
// - DockNodeHideHostWindow()
16012
// - ImGuiDockNodeFindInfoResults
16013
// - DockNodeFindInfo()
16014
// - DockNodeFindWindowByID()
16015
// - DockNodeUpdateFlagsAndCollapse()
16016
// - DockNodeUpdateHasCentralNodeFlag()
16017
// - DockNodeUpdateVisibleFlag()
16018
// - DockNodeStartMouseMovingWindow()
16019
// - DockNodeUpdate()
16020
// - DockNodeUpdateWindowMenu()
16021
// - DockNodeBeginAmendTabBar()
16022
// - DockNodeEndAmendTabBar()
16023
// - DockNodeUpdateTabBar()
16024
// - DockNodeAddTabBar()
16025
// - DockNodeRemoveTabBar()
16026
// - DockNodeIsDropAllowedOne()
16027
// - DockNodeIsDropAllowed()
16028
// - DockNodeCalcTabBarLayout()
16029
// - DockNodeCalcSplitRects()
16030
// - DockNodeCalcDropRectsAndTestMousePos()
16031
// - DockNodePreviewDockSetup()
16032
// - DockNodePreviewDockRender()
16033
//-----------------------------------------------------------------------------
16034
16035
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16036
0
{
16037
0
    ID = id;
16038
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16039
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16040
0
    TabBar = NULL;
16041
0
    SplitAxis = ImGuiAxis_None;
16042
16043
0
    State = ImGuiDockNodeState_Unknown;
16044
0
    LastBgColor = IM_COL32_WHITE;
16045
0
    HostWindow = VisibleWindow = NULL;
16046
0
    CentralNode = OnlyNodeWithWindows = NULL;
16047
0
    CountNodeWithWindows = 0;
16048
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16049
0
    LastFocusedNodeId = 0;
16050
0
    SelectedTabId = 0;
16051
0
    WantCloseTabId = 0;
16052
0
    RefViewportId = 0;
16053
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16054
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16055
0
    IsVisible = true;
16056
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16057
0
    IsBgDrawnThisFrame = false;
16058
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16059
0
}
16060
16061
ImGuiDockNode::~ImGuiDockNode()
16062
0
{
16063
0
    IM_DELETE(TabBar);
16064
0
    TabBar = NULL;
16065
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16066
0
}
16067
16068
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16069
0
{
16070
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16071
0
    if (tab_bar == NULL)
16072
0
        return -1;
16073
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16074
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16075
0
}
16076
16077
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16078
0
{
16079
0
    window->Hidden = true;
16080
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16081
0
}
16082
16083
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16084
0
{
16085
0
    ImGuiContext& g = *GImGui; (void)g;
16086
0
    if (window->DockNode)
16087
0
    {
16088
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16089
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16090
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16091
0
    }
16092
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16093
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16094
16095
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16096
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16097
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16098
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16099
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16100
16101
0
    node->Windows.push_back(window);
16102
0
    node->WantHiddenTabBarUpdate = true;
16103
0
    window->DockNode = node;
16104
0
    window->DockId = node->ID;
16105
0
    window->DockIsActive = (node->Windows.Size > 1);
16106
0
    window->DockTabWantClose = false;
16107
16108
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16109
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16110
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16111
0
    {
16112
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16113
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16114
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16115
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16116
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16117
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16118
0
    }
16119
16120
    // Add to tab bar if requested
16121
0
    if (add_to_tab_bar)
16122
0
    {
16123
0
        if (node->TabBar == NULL)
16124
0
        {
16125
0
            DockNodeAddTabBar(node);
16126
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16127
16128
            // Add existing windows
16129
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16130
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16131
0
        }
16132
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16133
0
    }
16134
16135
0
    DockNodeUpdateVisibleFlag(node);
16136
16137
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16138
0
    if (node->HostWindow)
16139
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16140
0
}
16141
16142
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16143
0
{
16144
0
    ImGuiContext& g = *GImGui;
16145
0
    IM_ASSERT(window->DockNode == node);
16146
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16147
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16148
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16149
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16150
16151
0
    window->DockNode = NULL;
16152
0
    window->DockIsActive = window->DockTabWantClose = false;
16153
0
    window->DockId = save_dock_id;
16154
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16155
0
    if (window->ParentWindow)
16156
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16157
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16158
16159
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16160
0
    {
16161
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16162
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16163
0
        window->Viewport = NULL;
16164
0
        window->ViewportId = 0;
16165
0
        window->ViewportOwned = false;
16166
0
        window->Hidden = true;
16167
0
    }
16168
16169
    // Remove window
16170
0
    bool erased = false;
16171
0
    for (int n = 0; n < node->Windows.Size; n++)
16172
0
        if (node->Windows[n] == window)
16173
0
        {
16174
0
            node->Windows.erase(node->Windows.Data + n);
16175
0
            erased = true;
16176
0
            break;
16177
0
        }
16178
0
    if (!erased)
16179
0
        IM_ASSERT(erased);
16180
0
    if (node->VisibleWindow == window)
16181
0
        node->VisibleWindow = NULL;
16182
16183
    // Remove tab and possibly tab bar
16184
0
    node->WantHiddenTabBarUpdate = true;
16185
0
    if (node->TabBar)
16186
0
    {
16187
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16188
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16189
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16190
0
            DockNodeRemoveTabBar(node);
16191
0
    }
16192
16193
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16194
0
    {
16195
        // Automatic dock node delete themselves if they are not holding at least one tab
16196
0
        DockContextRemoveNode(&g, node, true);
16197
0
        return;
16198
0
    }
16199
16200
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16201
0
    {
16202
0
        ImGuiWindow* remaining_window = node->Windows[0];
16203
        // Note: we used to transport viewport ownership here.
16204
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16205
0
    }
16206
16207
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16208
0
    DockNodeUpdateVisibleFlag(node);
16209
0
}
16210
16211
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16212
0
{
16213
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16214
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16215
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16216
0
    if (dst_node->ChildNodes[0])
16217
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16218
0
    if (dst_node->ChildNodes[1])
16219
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16220
0
    dst_node->SplitAxis = src_node->SplitAxis;
16221
0
    dst_node->SizeRef = src_node->SizeRef;
16222
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16223
0
}
16224
16225
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16226
0
{
16227
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16228
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16229
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16230
0
    if (src_tab_bar != NULL)
16231
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16232
16233
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16234
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16235
0
    if (move_tab_bar)
16236
0
    {
16237
0
        dst_node->TabBar = src_node->TabBar;
16238
0
        src_node->TabBar = NULL;
16239
0
    }
16240
16241
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16242
0
    for (ImGuiWindow* window : src_node->Windows)
16243
0
    {
16244
0
        window->DockNode = NULL;
16245
0
        window->DockIsActive = false;
16246
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16247
0
    }
16248
0
    src_node->Windows.clear();
16249
16250
0
    if (!move_tab_bar && src_node->TabBar)
16251
0
    {
16252
0
        if (dst_node->TabBar)
16253
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16254
0
        DockNodeRemoveTabBar(src_node);
16255
0
    }
16256
0
}
16257
16258
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16259
0
{
16260
0
    for (ImGuiWindow* window : node->Windows)
16261
0
    {
16262
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16263
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16264
0
    }
16265
0
}
16266
16267
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16268
0
{
16269
0
    if (node->HostWindow)
16270
0
    {
16271
0
        if (node->HostWindow->DockNodeAsHost == node)
16272
0
            node->HostWindow->DockNodeAsHost = NULL;
16273
0
        node->HostWindow = NULL;
16274
0
    }
16275
16276
0
    if (node->Windows.Size == 1)
16277
0
    {
16278
0
        node->VisibleWindow = node->Windows[0];
16279
0
        node->Windows[0]->DockIsActive = false;
16280
0
    }
16281
16282
0
    if (node->TabBar)
16283
0
        DockNodeRemoveTabBar(node);
16284
0
}
16285
16286
// Search function called once by root node in DockNodeUpdate()
16287
struct ImGuiDockNodeTreeInfo
16288
{
16289
    ImGuiDockNode*      CentralNode;
16290
    ImGuiDockNode*      FirstNodeWithWindows;
16291
    int                 CountNodesWithWindows;
16292
    //ImGuiWindowClass  WindowClassForMerges;
16293
16294
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16295
};
16296
16297
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16298
0
{
16299
0
    if (node->Windows.Size > 0)
16300
0
    {
16301
0
        if (info->FirstNodeWithWindows == NULL)
16302
0
            info->FirstNodeWithWindows = node;
16303
0
        info->CountNodesWithWindows++;
16304
0
    }
16305
0
    if (node->IsCentralNode())
16306
0
    {
16307
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16308
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16309
0
        info->CentralNode = node;
16310
0
    }
16311
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16312
0
        return;
16313
0
    if (node->ChildNodes[0])
16314
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16315
0
    if (node->ChildNodes[1])
16316
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16317
0
}
16318
16319
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16320
0
{
16321
0
    IM_ASSERT(id != 0);
16322
0
    for (ImGuiWindow* window : node->Windows)
16323
0
        if (window->ID == id)
16324
0
            return window;
16325
0
    return NULL;
16326
0
}
16327
16328
// - Remove inactive windows/nodes.
16329
// - Update visibility flag.
16330
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16331
0
{
16332
0
    ImGuiContext& g = *GImGui;
16333
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16334
16335
    // Inherit most flags
16336
0
    if (node->ParentNode)
16337
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16338
16339
    // Recurse into children
16340
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16341
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16342
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16343
0
    node->HasCentralNodeChild = false;
16344
0
    if (node->ChildNodes[0])
16345
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16346
0
    if (node->ChildNodes[1])
16347
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16348
16349
    // Remove inactive windows, collapse nodes
16350
    // Merge node flags overrides stored in windows
16351
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16352
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16353
0
    {
16354
0
        ImGuiWindow* window = node->Windows[window_n];
16355
0
        IM_ASSERT(window->DockNode == node);
16356
16357
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16358
0
        bool remove = false;
16359
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16360
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16361
0
        remove |= (window->DockTabWantClose);
16362
0
        if (remove)
16363
0
        {
16364
0
            window->DockTabWantClose = false;
16365
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16366
0
            {
16367
0
                DockNodeHideHostWindow(node);
16368
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16369
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16370
0
                return;
16371
0
            }
16372
0
            DockNodeRemoveWindow(node, window, node->ID);
16373
0
            window_n--;
16374
0
            continue;
16375
0
        }
16376
16377
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16378
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16379
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16380
0
    }
16381
0
    node->UpdateMergedFlags();
16382
16383
    // Auto-hide tab bar option
16384
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16385
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16386
0
        node->WantHiddenTabBarToggle = true;
16387
0
    node->WantHiddenTabBarUpdate = false;
16388
16389
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16390
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16391
0
        node->WantHiddenTabBarToggle = false;
16392
16393
    // Apply toggles at a single point of the frame (here!)
16394
0
    if (node->Windows.Size > 1)
16395
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16396
0
    else if (node->WantHiddenTabBarToggle)
16397
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16398
0
    node->WantHiddenTabBarToggle = false;
16399
16400
0
    DockNodeUpdateVisibleFlag(node);
16401
0
}
16402
16403
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16404
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16405
0
{
16406
0
    node->HasCentralNodeChild = false;
16407
0
    if (node->ChildNodes[0])
16408
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16409
0
    if (node->ChildNodes[1])
16410
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16411
0
    if (node->IsRootNode())
16412
0
    {
16413
0
        ImGuiDockNode* mark_node = node->CentralNode;
16414
0
        while (mark_node)
16415
0
        {
16416
0
            mark_node->HasCentralNodeChild = true;
16417
0
            mark_node = mark_node->ParentNode;
16418
0
        }
16419
0
    }
16420
0
}
16421
16422
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16423
0
{
16424
    // Update visibility flag
16425
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16426
0
    is_visible |= (node->Windows.Size > 0);
16427
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16428
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16429
0
    node->IsVisible = is_visible;
16430
0
}
16431
16432
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16433
0
{
16434
0
    ImGuiContext& g = *GImGui;
16435
0
    IM_ASSERT(node->WantMouseMove == true);
16436
0
    StartMouseMovingWindow(window);
16437
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16438
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16439
0
    node->WantMouseMove = false;
16440
0
}
16441
16442
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16443
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16444
0
{
16445
0
    DockNodeUpdateFlagsAndCollapse(node);
16446
16447
    // - Setup central node pointers
16448
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16449
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16450
0
    ImGuiDockNodeTreeInfo info;
16451
0
    DockNodeFindInfo(node, &info);
16452
0
    node->CentralNode = info.CentralNode;
16453
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16454
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16455
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16456
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16457
16458
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16459
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16460
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16461
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16462
0
    {
16463
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16464
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16465
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16466
0
            {
16467
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16468
0
                break;
16469
0
            }
16470
0
    }
16471
16472
0
    ImGuiDockNode* mark_node = node->CentralNode;
16473
0
    while (mark_node)
16474
0
    {
16475
0
        mark_node->HasCentralNodeChild = true;
16476
0
        mark_node = mark_node->ParentNode;
16477
0
    }
16478
0
}
16479
16480
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16481
0
{
16482
    // Remove ourselves from any previous different host window
16483
    // This can happen if a user mistakenly does (see #4295 for details):
16484
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16485
    //  - N+1: NewFrame()                   // will create floating host window for that node
16486
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16487
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16488
0
        node->HostWindow->DockNodeAsHost = NULL;
16489
16490
0
    host_window->DockNodeAsHost = node;
16491
0
    node->HostWindow = host_window;
16492
0
}
16493
16494
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16495
0
{
16496
0
    ImGuiContext& g = *GImGui;
16497
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16498
0
    node->LastFrameAlive = g.FrameCount;
16499
0
    node->IsBgDrawnThisFrame = false;
16500
16501
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16502
0
    if (node->IsRootNode())
16503
0
        DockNodeUpdateForRootNode(node);
16504
16505
    // Remove tab bar if not needed
16506
0
    if (node->TabBar && node->IsNoTabBar())
16507
0
        DockNodeRemoveTabBar(node);
16508
16509
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16510
0
    bool want_to_hide_host_window = false;
16511
0
    if (node->IsFloatingNode())
16512
0
    {
16513
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16514
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16515
0
                want_to_hide_host_window = true;
16516
0
        if (node->CountNodeWithWindows == 0)
16517
0
            want_to_hide_host_window = true;
16518
0
    }
16519
0
    if (want_to_hide_host_window)
16520
0
    {
16521
0
        if (node->Windows.Size == 1)
16522
0
        {
16523
            // Floating window pos/size is authoritative
16524
0
            ImGuiWindow* single_window = node->Windows[0];
16525
0
            node->Pos = single_window->Pos;
16526
0
            node->Size = single_window->SizeFull;
16527
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16528
16529
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16530
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16531
0
                FocusWindow(single_window);
16532
0
            if (node->HostWindow)
16533
0
            {
16534
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16535
0
                single_window->Viewport = node->HostWindow->Viewport;
16536
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16537
0
                if (node->HostWindow->ViewportOwned)
16538
0
                {
16539
0
                    single_window->Viewport->ID = single_window->ID;
16540
0
                    single_window->Viewport->Window = single_window;
16541
0
                    single_window->ViewportOwned = true;
16542
0
                }
16543
0
            }
16544
0
            node->RefViewportId = single_window->ViewportId;
16545
0
        }
16546
16547
0
        DockNodeHideHostWindow(node);
16548
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16549
0
        node->WantCloseAll = false;
16550
0
        node->WantCloseTabId = 0;
16551
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16552
0
        node->LastFrameActive = g.FrameCount;
16553
16554
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16555
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16556
0
        return;
16557
0
    }
16558
16559
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16560
    // while the expected visible window is resizing itself.
16561
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16562
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16563
    //   N+0: Begin(): window created (with no known size), node is created
16564
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16565
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16566
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16567
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16568
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16569
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16570
0
    {
16571
0
        IM_ASSERT(node->Windows.Size > 0);
16572
0
        ImGuiWindow* ref_window = NULL;
16573
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16574
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16575
0
        if (ref_window == NULL)
16576
0
            ref_window = node->Windows[0];
16577
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16578
0
        {
16579
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16580
0
            return;
16581
0
        }
16582
0
    }
16583
16584
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16585
16586
    // Decide if the node will have a close button and a window menu button
16587
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16588
0
    node->HasCloseButton = false;
16589
0
    for (ImGuiWindow* window : node->Windows)
16590
0
    {
16591
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16592
0
        node->HasCloseButton |= window->HasCloseButton;
16593
0
        window->DockIsActive = (node->Windows.Size > 1);
16594
0
    }
16595
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16596
0
        node->HasCloseButton = false;
16597
16598
    // Bind or create host window
16599
0
    ImGuiWindow* host_window = NULL;
16600
0
    bool beginned_into_host_window = false;
16601
0
    if (node->IsDockSpace())
16602
0
    {
16603
        // [Explicit root dockspace node]
16604
0
        IM_ASSERT(node->HostWindow);
16605
0
        host_window = node->HostWindow;
16606
0
    }
16607
0
    else
16608
0
    {
16609
        // [Automatic root or child nodes]
16610
0
        if (node->IsRootNode() && node->IsVisible)
16611
0
        {
16612
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16613
16614
            // Sync Pos
16615
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16616
0
                SetNextWindowPos(ref_window->Pos);
16617
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16618
0
                SetNextWindowPos(node->Pos);
16619
16620
            // Sync Size
16621
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16622
0
                SetNextWindowSize(ref_window->SizeFull);
16623
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16624
0
                SetNextWindowSize(node->Size);
16625
16626
            // Sync Collapsed
16627
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16628
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16629
16630
            // Sync Viewport
16631
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16632
0
                SetNextWindowViewport(ref_window->ViewportId);
16633
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
16634
0
                SetNextWindowViewport(node->RefViewportId);
16635
16636
0
            SetNextWindowClass(&node->WindowClass);
16637
16638
            // Begin into the host window
16639
0
            char window_label[20];
16640
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16641
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16642
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16643
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16644
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16645
16646
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16647
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16648
0
            Begin(window_label, NULL, window_flags);
16649
0
            PopStyleVar();
16650
0
            beginned_into_host_window = true;
16651
16652
0
            host_window = g.CurrentWindow;
16653
0
            DockNodeSetupHostWindow(node, host_window);
16654
0
            host_window->DC.CursorPos = host_window->Pos;
16655
0
            node->Pos = host_window->Pos;
16656
0
            node->Size = host_window->Size;
16657
16658
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16659
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16660
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16661
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16662
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16663
            // after the dock host window, losing their top-most status.
16664
0
            if (node->HostWindow->Appearing)
16665
0
                BringWindowToDisplayFront(node->HostWindow);
16666
16667
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16668
0
        }
16669
0
        else if (node->ParentNode)
16670
0
        {
16671
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16672
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16673
0
        }
16674
0
        if (node->WantMouseMove && node->HostWindow)
16675
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16676
0
    }
16677
0
    node->RefViewportId = 0; // Clear when we have a host window
16678
16679
    // Update focused node (the one whose title bar is highlight) within a node tree
16680
0
    if (node->IsSplitNode())
16681
0
        IM_ASSERT(node->TabBar == NULL);
16682
0
    if (node->IsRootNode())
16683
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16684
0
            while (p_window != NULL && p_window->DockNode != NULL)
16685
0
            {
16686
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16687
0
                if (p_node == node)
16688
0
                {
16689
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16690
0
                    break;
16691
0
                }
16692
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16693
0
            }
16694
16695
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16696
0
    ImGuiDockNode* central_node = node->CentralNode;
16697
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16698
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16699
0
    if (central_node_hole)
16700
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16701
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16702
0
                central_node_hole_register_hit_test_hole = false;
16703
0
    if (central_node_hole_register_hit_test_hole)
16704
0
    {
16705
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16706
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16707
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16708
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16709
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16710
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16711
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16712
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16713
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16714
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16715
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16716
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16717
0
        if (central_node_hole && !hole_rect.IsInverted())
16718
0
        {
16719
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16720
0
            if (host_window->ParentWindow)
16721
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16722
0
        }
16723
0
    }
16724
16725
    // Update position/size, process and draw resizing splitters
16726
0
    if (node->IsRootNode() && host_window)
16727
0
    {
16728
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16729
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
16730
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
16731
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
16732
0
        DockNodeTreeUpdateSplitter(node);
16733
0
        PopStyleColor(3);
16734
0
    }
16735
16736
    // Draw empty node background (currently can only be the Central Node)
16737
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16738
0
    {
16739
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16740
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16741
0
        if (node->LastBgColor != 0)
16742
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16743
0
        node->IsBgDrawnThisFrame = true;
16744
0
    }
16745
16746
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16747
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16748
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16749
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16750
0
    if (render_dockspace_bg && node->IsVisible)
16751
0
    {
16752
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16753
0
        if (central_node_hole)
16754
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16755
0
        else
16756
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16757
0
    }
16758
16759
    // Draw and populate Tab Bar
16760
0
    if (host_window)
16761
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16762
0
    if (host_window && node->Windows.Size > 0)
16763
0
    {
16764
0
        DockNodeUpdateTabBar(node, host_window);
16765
0
    }
16766
0
    else
16767
0
    {
16768
0
        node->WantCloseAll = false;
16769
0
        node->WantCloseTabId = 0;
16770
0
        node->IsFocused = false;
16771
0
    }
16772
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16773
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16774
0
    else if (node->Windows.Size > 0)
16775
0
        node->SelectedTabId = node->Windows[0]->TabId;
16776
16777
    // Draw payload drop target
16778
0
    if (host_window && node->IsVisible)
16779
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16780
0
            BeginDockableDragDropTarget(host_window);
16781
16782
    // We update this after DockNodeUpdateTabBar()
16783
0
    node->LastFrameActive = g.FrameCount;
16784
16785
    // Recurse into children
16786
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16787
0
    if (host_window)
16788
0
    {
16789
0
        if (node->ChildNodes[0])
16790
0
            DockNodeUpdate(node->ChildNodes[0]);
16791
0
        if (node->ChildNodes[1])
16792
0
            DockNodeUpdate(node->ChildNodes[1]);
16793
16794
        // Render outer borders last (after the tab bar)
16795
0
        if (node->IsRootNode())
16796
0
            RenderWindowOuterBorders(host_window);
16797
0
    }
16798
16799
    // End host window
16800
0
    if (beginned_into_host_window) //-V1020
16801
0
        End();
16802
0
}
16803
16804
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16805
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16806
0
{
16807
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16808
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16809
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16810
0
        return d;
16811
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16812
0
}
16813
16814
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16815
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16816
// Custom overrides may want to decorate, group, sort entries.
16817
// Please note those are internal structures: if you copy this expect occasional breakage.
16818
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
16819
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16820
0
{
16821
0
    IM_UNUSED(ctx);
16822
0
    if (tab_bar->Tabs.Size == 1)
16823
0
    {
16824
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16825
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16826
0
            node->WantHiddenTabBarToggle = true;
16827
0
    }
16828
0
    else
16829
0
    {
16830
        // Display a selectable list of windows in this docking node
16831
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16832
0
        {
16833
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16834
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16835
0
                continue;
16836
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16837
0
                TabBarQueueFocus(tab_bar, tab);
16838
0
            SameLine();
16839
0
            Text("   ");
16840
0
        }
16841
0
    }
16842
0
}
16843
16844
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16845
0
{
16846
    // Try to position the menu so it is more likely to stays within the same viewport
16847
0
    ImGuiContext& g = *GImGui;
16848
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16849
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16850
0
    else
16851
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16852
0
    if (BeginPopup("#WindowMenu"))
16853
0
    {
16854
0
        node->IsFocused = true;
16855
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16856
0
        EndPopup();
16857
0
    }
16858
0
}
16859
16860
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16861
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16862
0
{
16863
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16864
0
        return false;
16865
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16866
0
        return false;
16867
0
    if (node->TabBar->ID == 0)
16868
0
        return false;
16869
0
    Begin(node->HostWindow->Name);
16870
0
    PushOverrideID(node->ID);
16871
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
16872
0
    IM_UNUSED(ret);
16873
0
    IM_ASSERT(ret);
16874
0
    return true;
16875
0
}
16876
16877
void ImGui::DockNodeEndAmendTabBar()
16878
0
{
16879
0
    EndTabBar();
16880
0
    PopID();
16881
0
    End();
16882
0
}
16883
16884
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16885
0
{
16886
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16887
0
    ImGuiContext& g = *GImGui;
16888
0
    if (g.NavWindowingTarget)
16889
0
        return (g.NavWindowingTarget->DockNode == node);
16890
16891
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16892
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16893
0
    {
16894
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16895
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16896
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16897
0
            parent_window = parent_window->ParentWindow->RootWindow;
16898
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16899
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16900
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16901
0
                return true;
16902
0
    }
16903
0
    return false;
16904
0
}
16905
16906
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16907
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16908
0
{
16909
0
    ImGuiContext& g = *GImGui;
16910
0
    ImGuiStyle& style = g.Style;
16911
16912
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16913
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16914
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16915
0
    node->WantCloseAll = false;
16916
0
    node->WantCloseTabId = 0;
16917
16918
    // Decide if we should use a focused title bar color
16919
0
    bool is_focused = false;
16920
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16921
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16922
0
        is_focused = true;
16923
16924
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16925
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16926
0
    {
16927
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16928
0
        node->IsFocused = is_focused;
16929
0
        if (is_focused)
16930
0
            node->LastFrameFocused = g.FrameCount;
16931
0
        if (node->VisibleWindow)
16932
0
        {
16933
            // Notify root of visible window (used to display title in OS task bar)
16934
0
            if (is_focused || root_node->VisibleWindow == NULL)
16935
0
                root_node->VisibleWindow = node->VisibleWindow;
16936
0
            if (node->TabBar)
16937
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16938
0
        }
16939
0
        return;
16940
0
    }
16941
16942
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16943
0
    bool backup_skip_item = host_window->SkipItems;
16944
0
    if (!node->IsDockSpace())
16945
0
    {
16946
0
        host_window->SkipItems = false;
16947
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16948
0
    }
16949
16950
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16951
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16952
    // as docked windows themselves will override the stack with their own root ID.
16953
0
    PushOverrideID(node->ID);
16954
0
    ImGuiTabBar* tab_bar = node->TabBar;
16955
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16956
0
    if (tab_bar == NULL)
16957
0
    {
16958
0
        DockNodeAddTabBar(node);
16959
0
        tab_bar = node->TabBar;
16960
0
    }
16961
16962
0
    ImGuiID focus_tab_id = 0;
16963
0
    node->IsFocused = is_focused;
16964
16965
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16966
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16967
16968
    // In a dock node, the Collapse Button turns into the Window Menu button.
16969
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16970
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16971
0
    {
16972
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
16973
0
        DockNodeWindowMenuUpdate(node, tab_bar);
16974
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
16975
0
            focus_tab_id = tab_bar->NextSelectedTabId;
16976
0
        is_focused |= node->IsFocused;
16977
0
    }
16978
16979
    // Layout
16980
0
    ImRect title_bar_rect, tab_bar_rect;
16981
0
    ImVec2 window_menu_button_pos;
16982
0
    ImVec2 close_button_pos;
16983
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16984
16985
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16986
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16987
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16988
0
    {
16989
0
        ImGuiWindow* window = node->Windows[window_n];
16990
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16991
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16992
0
    }
16993
16994
    // Title bar
16995
0
    if (is_focused)
16996
0
        node->LastFrameFocused = g.FrameCount;
16997
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16998
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
16999
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17000
17001
    // Docking/Collapse button
17002
0
    if (has_window_menu_button)
17003
0
    {
17004
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17005
0
            OpenPopup("#WindowMenu");
17006
0
        if (IsItemActive())
17007
0
            focus_tab_id = tab_bar->SelectedTabId;
17008
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17009
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17010
0
    }
17011
17012
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17013
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17014
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17015
0
    {
17016
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17017
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17018
0
        tabs_unsorted_start = tab_n;
17019
0
    }
17020
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17021
0
    {
17022
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17023
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17024
0
        {
17025
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17026
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17027
0
        }
17028
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17029
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17030
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17031
0
    }
17032
17033
    // Apply NavWindow focus back to the tab bar
17034
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17035
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17036
17037
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17038
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17039
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17040
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17041
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17042
17043
    // Begin tab bar
17044
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17045
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17046
0
    if (!host_window->Collapsed && is_focused)
17047
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17048
0
    tab_bar->ID = GetID("#TabBar");
17049
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17050
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17051
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17052
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17053
17054
    // Backup style colors
17055
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17056
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17057
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17058
17059
    // Submit actual tabs
17060
0
    node->VisibleWindow = NULL;
17061
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17062
0
    {
17063
0
        ImGuiWindow* window = node->Windows[window_n];
17064
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17065
0
            continue;
17066
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17067
0
        {
17068
0
            ImGuiTabItemFlags tab_item_flags = 0;
17069
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17070
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17071
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17072
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17073
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17074
17075
            // Apply stored style overrides for the window
17076
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17077
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17078
17079
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17080
0
            bool tab_open = true;
17081
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17082
0
            if (!tab_open)
17083
0
                node->WantCloseTabId = window->TabId;
17084
0
            if (tab_bar->VisibleTabId == window->TabId)
17085
0
                node->VisibleWindow = window;
17086
17087
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17088
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17089
0
            window->DockTabItemRect = g.LastItemData.Rect;
17090
17091
            // Update navigation ID on menu layer
17092
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17093
0
                host_window->NavLastIds[1] = window->TabId;
17094
0
        }
17095
0
    }
17096
17097
    // Restore style colors
17098
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17099
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17100
17101
    // Notify root of visible window (used to display title in OS task bar)
17102
0
    if (node->VisibleWindow)
17103
0
        if (is_focused || root_node->VisibleWindow == NULL)
17104
0
            root_node->VisibleWindow = node->VisibleWindow;
17105
17106
    // Close button (after VisibleWindow was updated)
17107
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17108
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17109
0
    const bool close_button_is_visible = node->HasCloseButton;
17110
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17111
0
    if (close_button_is_visible)
17112
0
    {
17113
0
        if (!close_button_is_enabled)
17114
0
        {
17115
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17116
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17117
0
        }
17118
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17119
0
        {
17120
0
            node->WantCloseAll = true;
17121
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17122
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17123
0
        }
17124
        //if (IsItemActive())
17125
        //    focus_tab_id = tab_bar->SelectedTabId;
17126
0
        if (!close_button_is_enabled)
17127
0
        {
17128
0
            PopStyleColor();
17129
0
            PopItemFlag();
17130
0
        }
17131
0
    }
17132
17133
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17134
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17135
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17136
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17137
0
    {
17138
        // AllowOverlap mode required for appending into dock node tab bar,
17139
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17140
0
        bool held;
17141
0
        KeepAliveID(title_bar_id);
17142
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17143
0
        if (g.HoveredId == title_bar_id)
17144
0
        {
17145
0
            g.LastItemData.ID = title_bar_id;
17146
0
        }
17147
0
        if (held)
17148
0
        {
17149
0
            if (IsMouseClicked(0))
17150
0
                focus_tab_id = tab_bar->SelectedTabId;
17151
17152
            // Forward moving request to selected window
17153
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17154
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17155
0
        }
17156
0
    }
17157
17158
    // Forward focus from host node to selected window
17159
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17160
    //    focus_tab_id = tab_bar->SelectedTabId;
17161
17162
    // When clicked on a tab we requested focus to the docked child
17163
    // This overrides the value set by "forward focus from host node to selected window".
17164
0
    if (tab_bar->NextSelectedTabId)
17165
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17166
17167
    // Apply navigation focus
17168
0
    if (focus_tab_id != 0)
17169
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17170
0
            if (tab->Window)
17171
0
            {
17172
0
                FocusWindow(tab->Window);
17173
0
                NavInitWindow(tab->Window, false);
17174
0
            }
17175
17176
0
    EndTabBar();
17177
0
    PopID();
17178
17179
    // Restore SkipItems flag
17180
0
    if (!node->IsDockSpace())
17181
0
    {
17182
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17183
0
        host_window->SkipItems = backup_skip_item;
17184
0
    }
17185
0
}
17186
17187
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17188
0
{
17189
0
    IM_ASSERT(node->TabBar == NULL);
17190
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17191
0
}
17192
17193
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17194
0
{
17195
0
    if (node->TabBar == NULL)
17196
0
        return;
17197
0
    IM_DELETE(node->TabBar);
17198
0
    node->TabBar = NULL;
17199
0
}
17200
17201
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17202
0
{
17203
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17204
0
        return false;
17205
17206
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17207
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17208
0
    if (host_class->ClassId != payload_class->ClassId)
17209
0
    {
17210
0
        bool pass = false;
17211
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17212
0
            pass = true;
17213
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17214
0
            pass = true;
17215
0
        if (!pass)
17216
0
            return false;
17217
0
    }
17218
17219
    // Prevent docking any window created above a popup
17220
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17221
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17222
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17223
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17224
0
    ImGuiContext& g = *GImGui;
17225
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17226
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17227
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17228
0
                return false;
17229
17230
0
    return true;
17231
0
}
17232
17233
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17234
0
{
17235
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17236
0
        return true;
17237
17238
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17239
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17240
0
    {
17241
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17242
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
17243
0
            return true;
17244
0
    }
17245
0
    return false;
17246
0
}
17247
17248
// window menu button == collapse button when not in a dock node.
17249
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17250
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17251
0
{
17252
0
    ImGuiContext& g = *GImGui;
17253
0
    ImGuiStyle& style = g.Style;
17254
17255
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17256
0
    if (out_title_rect) { *out_title_rect = r; }
17257
17258
0
    r.Min.x += style.WindowBorderSize;
17259
0
    r.Max.x -= style.WindowBorderSize;
17260
17261
0
    float button_sz = g.FontSize;
17262
0
    r.Min.x += style.FramePadding.x;
17263
0
    r.Max.x -= style.FramePadding.x;
17264
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17265
0
    if (node->HasCloseButton)
17266
0
    {
17267
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17268
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17269
0
    }
17270
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17271
0
    {
17272
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17273
0
    }
17274
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17275
0
    {
17276
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17277
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17278
0
    }
17279
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17280
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17281
0
}
17282
17283
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17284
0
{
17285
0
    ImGuiContext& g = *GImGui;
17286
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17287
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17288
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17289
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17290
17291
    // Distribute size on given axis (with a desired size or equally)
17292
0
    const float w_avail = size_old[axis] - dock_spacing;
17293
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17294
0
    {
17295
0
        size_new[axis] = size_new_desired[axis];
17296
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17297
0
    }
17298
0
    else
17299
0
    {
17300
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17301
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17302
0
    }
17303
17304
    // Position each node
17305
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17306
0
    {
17307
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17308
0
    }
17309
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17310
0
    {
17311
0
        pos_new[axis] = pos_old[axis];
17312
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17313
0
    }
17314
0
}
17315
17316
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17317
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17318
0
{
17319
0
    ImGuiContext& g = *GImGui;
17320
17321
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17322
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17323
0
    float hs_w; // Half-size, longer axis
17324
0
    float hs_h; // Half-size, smaller axis
17325
0
    ImVec2 off; // Distance from edge or center
17326
0
    if (outer_docking)
17327
0
    {
17328
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17329
        //hs_h = ImTrunc(hs_w * 0.15f);
17330
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17331
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17332
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17333
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17334
0
    }
17335
0
    else
17336
0
    {
17337
0
        hs_w = ImTrunc(hs_for_central_nodes);
17338
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17339
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17340
0
    }
17341
17342
0
    ImVec2 c = ImTrunc(parent.GetCenter());
17343
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17344
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17345
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17346
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17347
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17348
17349
0
    if (test_mouse_pos == NULL)
17350
0
        return false;
17351
17352
0
    ImRect hit_r = out_r;
17353
0
    if (!outer_docking)
17354
0
    {
17355
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17356
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
17357
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17358
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17359
0
        float r_threshold_center = hs_w * 1.4f;
17360
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17361
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17362
0
            return (dir == ImGuiDir_None);
17363
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17364
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17365
0
    }
17366
0
    return hit_r.Contains(*test_mouse_pos);
17367
0
}
17368
17369
// host_node may be NULL if the window doesn't have a DockNode already.
17370
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17371
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17372
0
{
17373
0
    ImGuiContext& g = *GImGui;
17374
17375
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17376
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17377
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17378
0
    if (payload_node == NULL)
17379
0
        payload_node = payload_window->DockNodeAsHost;
17380
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17381
0
    if (ref_node_for_rect)
17382
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17383
17384
    // Filter, figure out where we are allowed to dock
17385
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17386
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17387
0
    data->IsCenterAvailable = true;
17388
0
    if (is_outer_docking)
17389
0
        data->IsCenterAvailable = false;
17390
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17391
0
        data->IsCenterAvailable = false;
17392
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17393
0
        data->IsCenterAvailable = false;
17394
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17395
0
        data->IsCenterAvailable = false;
17396
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17397
0
        data->IsCenterAvailable = false;
17398
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17399
0
        data->IsCenterAvailable = false;
17400
17401
0
    data->IsSidesAvailable = true;
17402
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17403
0
        data->IsSidesAvailable = false;
17404
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17405
0
        data->IsSidesAvailable = false;
17406
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17407
0
        data->IsSidesAvailable = false;
17408
17409
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17410
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17411
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17412
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17413
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17414
17415
    // Calculate drop shapes geometry for allowed splitting directions
17416
0
    IM_ASSERT(ImGuiDir_None == -1);
17417
0
    data->SplitNode = host_node;
17418
0
    data->SplitDir = ImGuiDir_None;
17419
0
    data->IsSplitDirExplicit = false;
17420
0
    if (!host_window->Collapsed)
17421
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17422
0
        {
17423
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17424
0
                continue;
17425
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17426
0
                continue;
17427
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17428
0
            {
17429
0
                data->SplitDir = (ImGuiDir)dir;
17430
0
                data->IsSplitDirExplicit = true;
17431
0
            }
17432
0
        }
17433
17434
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17435
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17436
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17437
0
        data->IsDropAllowed = false;
17438
17439
    // Calculate split area
17440
0
    data->SplitRatio = 0.0f;
17441
0
    if (data->SplitDir != ImGuiDir_None)
17442
0
    {
17443
0
        ImGuiDir split_dir = data->SplitDir;
17444
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17445
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17446
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17447
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17448
17449
        // Calculate split ratio so we can pass it down the docking request
17450
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17451
0
        data->FutureNode.Pos = pos_new;
17452
0
        data->FutureNode.Size = size_new;
17453
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17454
0
    }
17455
0
}
17456
17457
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17458
0
{
17459
0
    ImGuiContext& g = *GImGui;
17460
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17461
17462
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17463
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17464
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17465
17466
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17467
0
    int overlay_draw_lists_count = 0;
17468
0
    ImDrawList* overlay_draw_lists[2];
17469
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17470
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17471
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17472
17473
    // Draw main preview rectangle
17474
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17475
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17476
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17477
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17478
17479
    // Display area preview
17480
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17481
0
    if (data->IsDropAllowed)
17482
0
    {
17483
0
        ImRect overlay_rect = data->FutureNode.Rect();
17484
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17485
0
            overlay_rect.Min.y += GetFrameHeight();
17486
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17487
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17488
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17489
0
    }
17490
17491
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17492
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17493
0
    {
17494
        // Compute target tab bar geometry so we can locate our preview tabs
17495
0
        ImRect tab_bar_rect;
17496
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17497
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17498
0
        if (host_node && host_node->TabBar)
17499
0
        {
17500
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17501
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17502
0
            else
17503
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17504
0
        }
17505
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17506
0
        {
17507
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17508
0
        }
17509
17510
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17511
0
        if (root_payload->DockNodeAsHost)
17512
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17513
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17514
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17515
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17516
0
        {
17517
            // DockNode's TabBar may have non-window Tabs manually appended by user
17518
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17519
0
            if (tab_bar_with_payload && payload_window == NULL)
17520
0
                continue;
17521
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17522
0
                continue;
17523
17524
            // Calculate the tab bounding box for each payload window
17525
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17526
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17527
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17528
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17529
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17530
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17531
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17532
0
            {
17533
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17534
0
                if (!tab_bar_rect.Contains(tab_bb))
17535
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17536
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17537
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17538
0
                if (!tab_bar_rect.Contains(tab_bb))
17539
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17540
0
            }
17541
0
            PopStyleColor();
17542
0
        }
17543
0
    }
17544
17545
    // Display drop boxes
17546
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17547
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17548
0
    {
17549
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17550
0
        {
17551
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17552
0
            ImRect draw_r_in = draw_r;
17553
0
            draw_r_in.Expand(-2.0f);
17554
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17555
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17556
0
            {
17557
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17558
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17559
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17560
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17561
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17562
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17563
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17564
0
            }
17565
0
        }
17566
17567
        // Stop after ImGuiDir_None
17568
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17569
0
            return;
17570
0
    }
17571
0
}
17572
17573
//-----------------------------------------------------------------------------
17574
// Docking: ImGuiDockNode Tree manipulation functions
17575
//-----------------------------------------------------------------------------
17576
// - DockNodeTreeSplit()
17577
// - DockNodeTreeMerge()
17578
// - DockNodeTreeUpdatePosSize()
17579
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17580
// - DockNodeTreeUpdateSplitter()
17581
// - DockNodeTreeFindFallbackLeafNode()
17582
// - DockNodeTreeFindNodeByPos()
17583
//-----------------------------------------------------------------------------
17584
17585
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17586
0
{
17587
0
    ImGuiContext& g = *GImGui;
17588
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17589
17590
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17591
0
    child_0->ParentNode = parent_node;
17592
17593
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17594
0
    child_1->ParentNode = parent_node;
17595
17596
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17597
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17598
0
    parent_node->ChildNodes[0] = child_0;
17599
0
    parent_node->ChildNodes[1] = child_1;
17600
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17601
0
    parent_node->SplitAxis = split_axis;
17602
0
    parent_node->VisibleWindow = NULL;
17603
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17604
17605
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17606
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17607
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17608
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17609
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
17610
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
17611
17612
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17613
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17614
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17615
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17616
17617
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17618
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17619
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17620
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17621
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17622
0
    child_0->UpdateMergedFlags();
17623
0
    child_1->UpdateMergedFlags();
17624
0
    parent_node->UpdateMergedFlags();
17625
0
    if (child_inheritor->IsCentralNode())
17626
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17627
0
}
17628
17629
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17630
0
{
17631
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17632
0
    ImGuiContext& g = *GImGui;
17633
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17634
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17635
0
    IM_ASSERT(child_0 || child_1);
17636
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17637
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17638
0
    {
17639
0
        IM_ASSERT(parent_node->TabBar == NULL);
17640
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17641
0
    }
17642
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17643
17644
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17645
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17646
0
    if (child_0)
17647
0
    {
17648
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17649
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17650
0
    }
17651
0
    if (child_1)
17652
0
    {
17653
0
        DockNodeMoveWindows(parent_node, child_1);
17654
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17655
0
    }
17656
0
    DockNodeApplyPosSizeToWindows(parent_node);
17657
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17658
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17659
0
    parent_node->SizeRef = backup_last_explicit_size;
17660
17661
    // Flags transfer
17662
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17663
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17664
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17665
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17666
0
    parent_node->UpdateMergedFlags();
17667
17668
0
    if (child_0)
17669
0
    {
17670
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17671
0
        IM_DELETE(child_0);
17672
0
    }
17673
0
    if (child_1)
17674
0
    {
17675
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17676
0
        IM_DELETE(child_1);
17677
0
    }
17678
0
}
17679
17680
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17681
// (Depth-first, Pre-Order)
17682
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17683
0
{
17684
    // During the regular dock node update we write to all nodes.
17685
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17686
0
    ImGuiContext& g = *GImGui;
17687
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17688
0
    if (write_to_node)
17689
0
    {
17690
0
        node->Pos = pos;
17691
0
        node->Size = size;
17692
0
    }
17693
17694
0
    if (node->IsLeafNode())
17695
0
        return;
17696
17697
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17698
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17699
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17700
0
    ImVec2 child_0_size = size, child_1_size = size;
17701
17702
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17703
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17704
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17705
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17706
17707
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17708
0
    {
17709
0
        const float spacing = g.Style.DockingSeparatorSize;
17710
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17711
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17712
17713
        // Size allocation policy
17714
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17715
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17716
17717
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17718
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
17719
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17720
17721
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17722
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17723
0
        {
17724
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17725
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17726
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17727
0
        }
17728
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17729
0
        {
17730
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17731
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17732
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17733
0
        }
17734
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17735
0
        {
17736
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17737
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17738
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17739
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
17740
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17741
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17742
0
        }
17743
17744
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17745
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17746
0
        {
17747
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17748
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17749
0
        }
17750
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17751
0
        {
17752
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17753
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17754
0
        }
17755
0
        else
17756
0
        {
17757
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17758
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17759
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
17760
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17761
0
        }
17762
17763
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17764
0
    }
17765
17766
0
    if (only_write_to_single_node == NULL)
17767
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17768
17769
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17770
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17771
0
    if (child_0_recurse)
17772
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17773
0
    if (child_1_recurse)
17774
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17775
0
}
17776
17777
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17778
0
{
17779
0
    if (node->IsLeafNode())
17780
0
    {
17781
0
        touching_nodes->push_back(node);
17782
0
        return;
17783
0
    }
17784
0
    if (node->ChildNodes[0]->IsVisible)
17785
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17786
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17787
0
    if (node->ChildNodes[1]->IsVisible)
17788
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17789
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17790
0
}
17791
17792
// (Depth-First, Pre-Order)
17793
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17794
0
{
17795
0
    if (node->IsLeafNode())
17796
0
        return;
17797
17798
0
    ImGuiContext& g = *GImGui;
17799
17800
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17801
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17802
0
    if (child_0->IsVisible && child_1->IsVisible)
17803
0
    {
17804
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17805
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17806
0
        IM_ASSERT(axis != ImGuiAxis_None);
17807
0
        ImRect bb;
17808
0
        bb.Min = child_0->Pos;
17809
0
        bb.Max = child_1->Pos;
17810
0
        bb.Min[axis] += child_0->Size[axis];
17811
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17812
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17813
17814
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17815
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17816
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17817
0
        {
17818
0
            ImGuiWindow* window = g.CurrentWindow;
17819
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17820
0
        }
17821
0
        else
17822
0
        {
17823
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17824
            //bb.Max[axis] -= 1;
17825
0
            PushID(node->ID);
17826
17827
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17828
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17829
0
            float min_size = g.Style.WindowMinSize[axis];
17830
0
            float resize_limits[2];
17831
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17832
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17833
17834
0
            ImGuiID splitter_id = GetID("##Splitter");
17835
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17836
0
            {
17837
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17838
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17839
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17840
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17841
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17842
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17843
17844
                // [DEBUG] Render touching nodes & limits
17845
                /*
17846
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17847
                for (int n = 0; n < 2; n++)
17848
                {
17849
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17850
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17851
                    if (axis == ImGuiAxis_X)
17852
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17853
                    else
17854
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17855
                }
17856
                */
17857
0
            }
17858
17859
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17860
0
            float cur_size_0 = child_0->Size[axis];
17861
0
            float cur_size_1 = child_1->Size[axis];
17862
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17863
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17864
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17865
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17866
0
            {
17867
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17868
0
                {
17869
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17870
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17871
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17872
17873
                    // Lock the size of every node that is a sibling of the node we are touching
17874
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17875
0
                    for (int side_n = 0; side_n < 2; side_n++)
17876
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17877
0
                        {
17878
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17879
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17880
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17881
0
                            while (touching_node->ParentNode != node)
17882
0
                            {
17883
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17884
0
                                {
17885
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17886
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17887
0
                                    node_to_preserve->WantLockSizeOnce = true;
17888
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17889
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17890
0
                                }
17891
0
                                touching_node = touching_node->ParentNode;
17892
0
                            }
17893
0
                        }
17894
17895
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17896
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17897
0
                    MarkIniSettingsDirty();
17898
0
                }
17899
0
            }
17900
0
            PopID();
17901
0
        }
17902
0
    }
17903
17904
0
    if (child_0->IsVisible)
17905
0
        DockNodeTreeUpdateSplitter(child_0);
17906
0
    if (child_1->IsVisible)
17907
0
        DockNodeTreeUpdateSplitter(child_1);
17908
0
}
17909
17910
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17911
0
{
17912
0
    if (node->IsLeafNode())
17913
0
        return node;
17914
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17915
0
        return leaf_node;
17916
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17917
0
        return leaf_node;
17918
0
    return NULL;
17919
0
}
17920
17921
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17922
0
{
17923
0
    if (!node->IsVisible)
17924
0
        return NULL;
17925
17926
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17927
0
    ImRect r(node->Pos, node->Pos + node->Size);
17928
0
    r.Expand(dock_spacing * 0.5f);
17929
0
    bool inside = r.Contains(pos);
17930
0
    if (!inside)
17931
0
        return NULL;
17932
17933
0
    if (node->IsLeafNode())
17934
0
        return node;
17935
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17936
0
        return hovered_node;
17937
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17938
0
        return hovered_node;
17939
17940
    // This means we are hovering over the splitter/spacing of a parent node
17941
0
    return node;
17942
0
}
17943
17944
//-----------------------------------------------------------------------------
17945
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17946
//-----------------------------------------------------------------------------
17947
// - SetWindowDock() [Internal]
17948
// - DockSpace()
17949
// - DockSpaceOverViewport()
17950
//-----------------------------------------------------------------------------
17951
17952
// [Internal] Called via SetNextWindowDockID()
17953
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17954
0
{
17955
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17956
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17957
0
        return;
17958
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17959
17960
0
    if (window->DockId == dock_id)
17961
0
        return;
17962
17963
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17964
0
    ImGuiContext* ctx = GImGui;
17965
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17966
0
        if (new_node->IsSplitNode())
17967
0
        {
17968
            // Policy: Find central node or latest focused node. We first move back to our root node.
17969
0
            new_node = DockNodeGetRootNode(new_node);
17970
0
            if (new_node->CentralNode)
17971
0
            {
17972
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17973
0
                dock_id = new_node->CentralNode->ID;
17974
0
            }
17975
0
            else
17976
0
            {
17977
0
                dock_id = new_node->LastFocusedNodeId;
17978
0
            }
17979
0
        }
17980
17981
0
    if (window->DockId == dock_id)
17982
0
        return;
17983
17984
0
    if (window->DockNode)
17985
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17986
0
    window->DockId = dock_id;
17987
0
}
17988
17989
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17990
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17991
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17992
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17993
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17994
0
{
17995
0
    ImGuiContext* ctx = GImGui;
17996
0
    ImGuiContext& g = *ctx;
17997
0
    ImGuiWindow* window = GetCurrentWindowRead();
17998
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17999
0
        return 0;
18000
18001
    // Early out if parent window is hidden/collapsed
18002
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18003
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18004
0
    if (window->SkipItems)
18005
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18006
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18007
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18008
18009
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18010
0
    IM_ASSERT(id != 0);
18011
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
18012
0
    if (!node)
18013
0
    {
18014
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18015
0
        node = DockContextAddNode(ctx, id);
18016
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18017
0
    }
18018
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18019
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18020
0
    node->SharedFlags = flags;
18021
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18022
18023
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18024
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18025
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18026
0
    {
18027
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18028
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18029
0
        return id;
18030
0
    }
18031
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18032
18033
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18034
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18035
0
    {
18036
0
        node->LastFrameAlive = g.FrameCount;
18037
0
        return id;
18038
0
    }
18039
18040
0
    const ImVec2 content_avail = GetContentRegionAvail();
18041
0
    ImVec2 size = ImTrunc(size_arg);
18042
0
    if (size.x <= 0.0f)
18043
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18044
0
    if (size.y <= 0.0f)
18045
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18046
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18047
18048
0
    node->Pos = window->DC.CursorPos;
18049
0
    node->Size = node->SizeRef = size;
18050
0
    SetNextWindowPos(node->Pos);
18051
0
    SetNextWindowSize(node->Size);
18052
0
    g.NextWindowData.PosUndock = false;
18053
18054
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18055
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18056
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18057
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18058
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18059
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18060
18061
0
    char title[256];
18062
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
18063
18064
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18065
0
    Begin(title, NULL, window_flags);
18066
0
    PopStyleVar();
18067
18068
0
    ImGuiWindow* host_window = g.CurrentWindow;
18069
0
    DockNodeSetupHostWindow(node, host_window);
18070
0
    host_window->ChildId = window->GetID(title);
18071
0
    node->OnlyNodeWithWindows = NULL;
18072
18073
0
    IM_ASSERT(node->IsRootNode());
18074
18075
    // We need to handle the rare case were a central node is missing.
18076
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18077
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18078
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18079
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18080
    // as it doesn't make sense for an empty dockspace to not have this property.
18081
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18082
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18083
18084
    // Update the node
18085
0
    DockNodeUpdate(node);
18086
18087
0
    End();
18088
18089
0
    ImRect bb(node->Pos, node->Pos + size);
18090
0
    ItemSize(size);
18091
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18092
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18093
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18094
18095
0
    return id;
18096
0
}
18097
18098
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18099
// The limitation with this call is that your window won't have a menu bar.
18100
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18101
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18102
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18103
0
{
18104
0
    if (viewport == NULL)
18105
0
        viewport = GetMainViewport();
18106
18107
0
    SetNextWindowPos(viewport->WorkPos);
18108
0
    SetNextWindowSize(viewport->WorkSize);
18109
0
    SetNextWindowViewport(viewport->ID);
18110
18111
0
    ImGuiWindowFlags host_window_flags = 0;
18112
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18113
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18114
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18115
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18116
18117
0
    char label[32];
18118
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
18119
18120
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18121
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18122
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18123
0
    Begin(label, NULL, host_window_flags);
18124
0
    PopStyleVar(3);
18125
18126
0
    ImGuiID dockspace_id = GetID("DockSpace");
18127
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18128
0
    End();
18129
18130
0
    return dockspace_id;
18131
0
}
18132
18133
//-----------------------------------------------------------------------------
18134
// Docking: Builder Functions
18135
//-----------------------------------------------------------------------------
18136
// Very early end-user API to manipulate dock nodes.
18137
// Only available in imgui_internal.h. Expect this API to change/break!
18138
// It is expected that those functions are all called _before_ the dockspace node submission.
18139
//-----------------------------------------------------------------------------
18140
// - DockBuilderDockWindow()
18141
// - DockBuilderGetNode()
18142
// - DockBuilderSetNodePos()
18143
// - DockBuilderSetNodeSize()
18144
// - DockBuilderAddNode()
18145
// - DockBuilderRemoveNode()
18146
// - DockBuilderRemoveNodeChildNodes()
18147
// - DockBuilderRemoveNodeDockedWindows()
18148
// - DockBuilderSplitNode()
18149
// - DockBuilderCopyNodeRec()
18150
// - DockBuilderCopyNode()
18151
// - DockBuilderCopyWindowSettings()
18152
// - DockBuilderCopyDockSpace()
18153
// - DockBuilderFinish()
18154
//-----------------------------------------------------------------------------
18155
18156
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18157
0
{
18158
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18159
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18160
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18161
0
    ImGuiID window_id = ImHashStr(window_name);
18162
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18163
0
    {
18164
        // Apply to created window
18165
0
        ImGuiID prev_node_id = window->DockId;
18166
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18167
0
        if (window->DockId != prev_node_id)
18168
0
            window->DockOrder = -1;
18169
0
    }
18170
0
    else
18171
0
    {
18172
        // Apply to settings
18173
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18174
0
        if (settings == NULL)
18175
0
            settings = CreateNewWindowSettings(window_name);
18176
0
        if (settings->DockId != node_id)
18177
0
            settings->DockOrder = -1;
18178
0
        settings->DockId = node_id;
18179
0
    }
18180
0
}
18181
18182
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18183
0
{
18184
0
    ImGuiContext* ctx = GImGui;
18185
0
    return DockContextFindNodeByID(ctx, node_id);
18186
0
}
18187
18188
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18189
0
{
18190
0
    ImGuiContext* ctx = GImGui;
18191
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18192
0
    if (node == NULL)
18193
0
        return;
18194
0
    node->Pos = pos;
18195
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18196
0
}
18197
18198
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18199
0
{
18200
0
    ImGuiContext* ctx = GImGui;
18201
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18202
0
    if (node == NULL)
18203
0
        return;
18204
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18205
0
    node->Size = node->SizeRef = size;
18206
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18207
0
}
18208
18209
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18210
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18211
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18212
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18213
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18214
// - Use (id == 0) to let the system allocate a node identifier.
18215
// - Existing node with a same id will be removed.
18216
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18217
0
{
18218
0
    ImGuiContext* ctx = GImGui;
18219
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18220
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18221
18222
0
    if (node_id != 0)
18223
0
        DockBuilderRemoveNode(node_id);
18224
18225
0
    ImGuiDockNode* node = NULL;
18226
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18227
0
    {
18228
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18229
0
        node = DockContextFindNodeByID(ctx, node_id);
18230
0
    }
18231
0
    else
18232
0
    {
18233
0
        node = DockContextAddNode(ctx, node_id);
18234
0
        node->SetLocalFlags(flags);
18235
0
    }
18236
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18237
0
    return node->ID;
18238
0
}
18239
18240
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18241
0
{
18242
0
    ImGuiContext* ctx = GImGui;
18243
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18244
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18245
18246
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18247
0
    if (node == NULL)
18248
0
        return;
18249
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18250
0
    DockBuilderRemoveNodeChildNodes(node_id);
18251
    // Node may have moved or deleted if e.g. any merge happened
18252
0
    node = DockContextFindNodeByID(ctx, node_id);
18253
0
    if (node == NULL)
18254
0
        return;
18255
0
    if (node->IsCentralNode() && node->ParentNode)
18256
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18257
0
    DockContextRemoveNode(ctx, node, true);
18258
0
}
18259
18260
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18261
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18262
0
{
18263
0
    ImGuiContext* ctx = GImGui;
18264
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18265
18266
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
18267
0
    if (root_id && root_node == NULL)
18268
0
        return;
18269
0
    bool has_central_node = false;
18270
18271
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18272
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18273
18274
    // Process active windows
18275
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18276
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18277
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18278
0
        {
18279
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18280
0
            if (want_removal)
18281
0
            {
18282
0
                if (node->IsCentralNode())
18283
0
                    has_central_node = true;
18284
0
                if (root_id != 0)
18285
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
18286
0
                if (root_node)
18287
0
                {
18288
0
                    DockNodeMoveWindows(root_node, node);
18289
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18290
0
                }
18291
0
                nodes_to_remove.push_back(node);
18292
0
            }
18293
0
        }
18294
18295
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18296
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18297
0
    if (root_node)
18298
0
    {
18299
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18300
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18301
0
    }
18302
18303
    // Apply to settings
18304
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
18305
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18306
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18307
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18308
0
                {
18309
0
                    settings->DockId = root_id;
18310
0
                    break;
18311
0
                }
18312
18313
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18314
0
    if (nodes_to_remove.Size > 1)
18315
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18316
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18317
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
18318
18319
0
    if (root_id == 0)
18320
0
    {
18321
0
        dc->Nodes.Clear();
18322
0
        dc->Requests.clear();
18323
0
    }
18324
0
    else if (has_central_node)
18325
0
    {
18326
0
        root_node->CentralNode = root_node;
18327
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18328
0
    }
18329
0
}
18330
18331
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18332
0
{
18333
    // Clear references in settings
18334
0
    ImGuiContext* ctx = GImGui;
18335
0
    ImGuiContext& g = *ctx;
18336
0
    if (clear_settings_refs)
18337
0
    {
18338
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18339
0
        {
18340
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18341
0
            if (!want_removal && settings->DockId != 0)
18342
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
18343
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18344
0
                        want_removal = true;
18345
0
            if (want_removal)
18346
0
                settings->DockId = 0;
18347
0
        }
18348
0
    }
18349
18350
    // Clear references in windows
18351
0
    for (int n = 0; n < g.Windows.Size; n++)
18352
0
    {
18353
0
        ImGuiWindow* window = g.Windows[n];
18354
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18355
0
        if (want_removal)
18356
0
        {
18357
0
            const ImGuiID backup_dock_id = window->DockId;
18358
0
            IM_UNUSED(backup_dock_id);
18359
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
18360
0
            if (!clear_settings_refs)
18361
0
                IM_ASSERT(window->DockId == backup_dock_id);
18362
0
        }
18363
0
    }
18364
0
}
18365
18366
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18367
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18368
// FIXME-DOCK: We are not exposing nor using split_outer.
18369
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18370
0
{
18371
0
    ImGuiContext& g = *GImGui;
18372
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18373
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18374
18375
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18376
0
    if (node == NULL)
18377
0
    {
18378
0
        IM_ASSERT(node != NULL);
18379
0
        return 0;
18380
0
    }
18381
18382
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18383
18384
0
    ImGuiDockRequest req;
18385
0
    req.Type = ImGuiDockRequestType_Split;
18386
0
    req.DockTargetWindow = NULL;
18387
0
    req.DockTargetNode = node;
18388
0
    req.DockPayload = NULL;
18389
0
    req.DockSplitDir = split_dir;
18390
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18391
0
    req.DockSplitOuter = false;
18392
0
    DockContextProcessDock(&g, &req);
18393
18394
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18395
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18396
0
    if (out_id_at_dir)
18397
0
        *out_id_at_dir = id_at_dir;
18398
0
    if (out_id_at_opposite_dir)
18399
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18400
0
    return id_at_dir;
18401
0
}
18402
18403
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18404
0
{
18405
0
    ImGuiContext& g = *GImGui;
18406
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18407
0
    dst_node->SharedFlags = src_node->SharedFlags;
18408
0
    dst_node->LocalFlags = src_node->LocalFlags;
18409
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18410
0
    dst_node->Pos = src_node->Pos;
18411
0
    dst_node->Size = src_node->Size;
18412
0
    dst_node->SizeRef = src_node->SizeRef;
18413
0
    dst_node->SplitAxis = src_node->SplitAxis;
18414
0
    dst_node->UpdateMergedFlags();
18415
18416
0
    out_node_remap_pairs->push_back(src_node->ID);
18417
0
    out_node_remap_pairs->push_back(dst_node->ID);
18418
18419
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18420
0
        if (src_node->ChildNodes[child_n])
18421
0
        {
18422
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18423
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18424
0
        }
18425
18426
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18427
0
    return dst_node;
18428
0
}
18429
18430
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18431
0
{
18432
0
    ImGuiContext* ctx = GImGui;
18433
0
    IM_ASSERT(src_node_id != 0);
18434
0
    IM_ASSERT(dst_node_id != 0);
18435
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18436
18437
0
    DockBuilderRemoveNode(dst_node_id);
18438
18439
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
18440
0
    IM_ASSERT(src_node != NULL);
18441
18442
0
    out_node_remap_pairs->clear();
18443
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18444
18445
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18446
0
}
18447
18448
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18449
0
{
18450
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18451
0
    if (src_window == NULL)
18452
0
        return;
18453
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18454
0
    {
18455
0
        dst_window->Pos = src_window->Pos;
18456
0
        dst_window->Size = src_window->Size;
18457
0
        dst_window->SizeFull = src_window->SizeFull;
18458
0
        dst_window->Collapsed = src_window->Collapsed;
18459
0
    }
18460
0
    else
18461
0
    {
18462
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18463
0
        if (!dst_settings)
18464
0
            dst_settings = CreateNewWindowSettings(dst_name);
18465
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18466
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18467
0
        {
18468
0
            dst_settings->ViewportPos = window_pos_2ih;
18469
0
            dst_settings->ViewportId = src_window->ViewportId;
18470
0
            dst_settings->Pos = ImVec2ih(0, 0);
18471
0
        }
18472
0
        else
18473
0
        {
18474
0
            dst_settings->Pos = window_pos_2ih;
18475
0
        }
18476
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18477
0
        dst_settings->Collapsed = src_window->Collapsed;
18478
0
    }
18479
0
}
18480
18481
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18482
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18483
0
{
18484
0
    ImGuiContext& g = *GImGui;
18485
0
    IM_ASSERT(src_dockspace_id != 0);
18486
0
    IM_ASSERT(dst_dockspace_id != 0);
18487
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18488
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18489
18490
    // Duplicate entire dock
18491
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18492
    // whereas we could attempt to at least keep them together in a new, same floating node.
18493
0
    ImVector<ImGuiID> node_remap_pairs;
18494
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18495
18496
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18497
    // (The windows associated to src_dockspace_id are staying in place)
18498
0
    ImVector<ImGuiID> src_windows;
18499
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18500
0
    {
18501
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18502
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18503
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18504
0
        src_windows.push_back(src_window_id);
18505
18506
        // Search in the remapping tables
18507
0
        ImGuiID src_dock_id = 0;
18508
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18509
0
            src_dock_id = src_window->DockId;
18510
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18511
0
            src_dock_id = src_window_settings->DockId;
18512
0
        ImGuiID dst_dock_id = 0;
18513
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18514
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18515
0
            {
18516
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18517
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18518
0
                break;
18519
0
            }
18520
18521
0
        if (dst_dock_id != 0)
18522
0
        {
18523
            // Docked windows gets redocked into the new node hierarchy.
18524
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18525
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18526
0
        }
18527
0
        else
18528
0
        {
18529
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18530
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18531
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18532
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18533
0
        }
18534
0
    }
18535
18536
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18537
    // Find those windows and move to them to the cloned dock node. This may be optional?
18538
    // Dock those are a second step as undocking would invalidate source dock nodes.
18539
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18540
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18541
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18542
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18543
0
        {
18544
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18545
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18546
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18547
0
            {
18548
0
                ImGuiWindow* window = node->Windows[window_n];
18549
0
                if (src_windows.contains(window->ID))
18550
0
                    continue;
18551
18552
                // Docked windows gets redocked into the new node hierarchy.
18553
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18554
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18555
0
            }
18556
0
        }
18557
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18558
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18559
0
}
18560
18561
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18562
void ImGui::DockBuilderFinish(ImGuiID root_id)
18563
0
{
18564
0
    ImGuiContext* ctx = GImGui;
18565
    //DockContextRebuild(ctx);
18566
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
18567
0
}
18568
18569
//-----------------------------------------------------------------------------
18570
// Docking: Begin/End Support Functions (called from Begin/End)
18571
//-----------------------------------------------------------------------------
18572
// - GetWindowAlwaysWantOwnTabBar()
18573
// - DockContextBindNodeToWindow()
18574
// - BeginDocked()
18575
// - BeginDockableDragDropSource()
18576
// - BeginDockableDragDropTarget()
18577
//-----------------------------------------------------------------------------
18578
18579
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18580
71.8k
{
18581
71.8k
    ImGuiContext& g = *GImGui;
18582
71.8k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18583
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18584
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18585
0
                return true;
18586
71.8k
    return false;
18587
71.8k
}
18588
18589
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18590
0
{
18591
0
    ImGuiContext& g = *ctx;
18592
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18593
0
    IM_ASSERT(window->DockNode == NULL);
18594
18595
    // We should not be docking into a split node (SetWindowDock should avoid this)
18596
0
    if (node && node->IsSplitNode())
18597
0
    {
18598
0
        DockContextProcessUndockWindow(ctx, window);
18599
0
        return NULL;
18600
0
    }
18601
18602
    // Create node
18603
0
    if (node == NULL)
18604
0
    {
18605
0
        node = DockContextAddNode(ctx, window->DockId);
18606
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18607
0
        node->LastFrameAlive = g.FrameCount;
18608
0
    }
18609
18610
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18611
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18612
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18613
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18614
0
    if (!node->IsVisible)
18615
0
    {
18616
0
        ImGuiDockNode* ancestor_node = node;
18617
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18618
0
            ancestor_node = ancestor_node->ParentNode;
18619
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18620
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18621
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18622
0
    }
18623
18624
    // Add window to node
18625
0
    bool node_was_visible = node->IsVisible;
18626
0
    DockNodeAddWindow(node, window, true);
18627
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18628
0
    IM_ASSERT(node == window->DockNode);
18629
0
    return node;
18630
0
}
18631
18632
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18633
0
{
18634
0
    ImGuiContext* ctx = GImGui;
18635
0
    ImGuiContext& g = *ctx;
18636
18637
    // Clear fields ahead so most early-out paths don't have to do it
18638
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18639
18640
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18641
0
    if (auto_dock_node)
18642
0
    {
18643
0
        if (window->DockId == 0)
18644
0
        {
18645
0
            IM_ASSERT(window->DockNode == NULL);
18646
0
            window->DockId = DockContextGenNodeID(ctx);
18647
0
        }
18648
0
    }
18649
0
    else
18650
0
    {
18651
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18652
0
        bool want_undock = false;
18653
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18654
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18655
0
        if (want_undock)
18656
0
        {
18657
0
            DockContextProcessUndockWindow(ctx, window);
18658
0
            return;
18659
0
        }
18660
0
    }
18661
18662
    // Bind to our dock node
18663
0
    ImGuiDockNode* node = window->DockNode;
18664
0
    if (node != NULL)
18665
0
        IM_ASSERT(window->DockId == node->ID);
18666
0
    if (window->DockId != 0 && node == NULL)
18667
0
    {
18668
0
        node = DockContextBindNodeToWindow(ctx, window);
18669
0
        if (node == NULL)
18670
0
            return;
18671
0
    }
18672
18673
#if 0
18674
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18675
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18676
    {
18677
        DockContextProcessUndockWindow(ctx, window);
18678
        return;
18679
    }
18680
#endif
18681
18682
    // Undock if our dockspace node disappeared
18683
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18684
0
    if (node->LastFrameAlive < g.FrameCount)
18685
0
    {
18686
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18687
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18688
0
        if (root_node->LastFrameAlive < g.FrameCount)
18689
0
            DockContextProcessUndockWindow(ctx, window);
18690
0
        else
18691
0
            window->DockIsActive = true;
18692
0
        return;
18693
0
    }
18694
18695
    // Store style overrides
18696
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18697
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18698
18699
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18700
    // and never create neither a host window neither a tab bar.
18701
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18702
0
    if (node->HostWindow == NULL)
18703
0
    {
18704
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18705
0
            window->DockIsActive = true;
18706
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
18707
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18708
0
        return;
18709
0
    }
18710
18711
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18712
0
    IM_ASSERT(node->HostWindow);
18713
0
    IM_ASSERT(node->IsLeafNode());
18714
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18715
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18716
18717
    // Undock if we are submitted earlier than the host window
18718
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18719
0
    {
18720
0
        DockContextProcessUndockWindow(ctx, window);
18721
0
        return;
18722
0
    }
18723
18724
    // Position/Size window
18725
0
    SetNextWindowPos(node->Pos);
18726
0
    SetNextWindowSize(node->Size);
18727
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18728
0
    window->DockIsActive = true;
18729
0
    window->DockNodeIsVisible = true;
18730
0
    window->DockTabIsVisible = false;
18731
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18732
0
        return;
18733
18734
    // When the window is selected we mark it as visible.
18735
0
    if (node->VisibleWindow == window)
18736
0
        window->DockTabIsVisible = true;
18737
18738
    // Update window flag
18739
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18740
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
18741
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
18742
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18743
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18744
0
    else
18745
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18746
18747
    // Save new dock order only if the window has been visible once already
18748
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18749
0
    if (node->TabBar && window->WasActive)
18750
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18751
18752
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18753
0
        *p_open = false;
18754
18755
    // Update ChildId to allow returning from Child to Parent with Escape
18756
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18757
0
    window->ChildId = parent_window->GetID(window->Name);
18758
0
}
18759
18760
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18761
132
{
18762
132
    ImGuiContext& g = *GImGui;
18763
132
    IM_ASSERT(g.ActiveId == window->MoveId);
18764
132
    IM_ASSERT(g.MovingWindow == window);
18765
132
    IM_ASSERT(g.CurrentWindow == window);
18766
18767
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
18768
132
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
18769
0
    {
18770
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
18771
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
18772
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
18773
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
18774
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
18775
0
        return;
18776
0
    }
18777
18778
132
    g.LastItemData.ID = window->MoveId;
18779
132
    window = window->RootWindowDockTree;
18780
132
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18781
132
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18782
132
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18783
16
    {
18784
16
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18785
16
        EndDragDropSource();
18786
18787
        // Store style overrides
18788
112
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18789
96
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18790
16
    }
18791
132
}
18792
18793
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18794
19
{
18795
19
    ImGuiContext* ctx = GImGui;
18796
19
    ImGuiContext& g = *ctx;
18797
18798
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18799
19
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18800
19
    if (!g.DragDropActive)
18801
0
        return;
18802
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18803
19
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18804
19
        return;
18805
18806
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18807
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18808
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18809
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18810
0
    {
18811
0
        EndDragDropTarget();
18812
0
        return;
18813
0
    }
18814
18815
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18816
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18817
0
    {
18818
        // Select target node
18819
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18820
0
        bool dock_into_floating_window = false;
18821
0
        ImGuiDockNode* node = NULL;
18822
0
        if (window->DockNodeAsHost)
18823
0
        {
18824
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18825
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18826
18827
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18828
            // In this case we need to fallback into any leaf mode, possibly the central node.
18829
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18830
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18831
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18832
0
        }
18833
0
        else
18834
0
        {
18835
0
            if (window->DockNode)
18836
0
                node = window->DockNode;
18837
0
            else
18838
0
                dock_into_floating_window = true; // Dock into a regular window
18839
0
        }
18840
18841
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18842
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18843
18844
        // Preview docking request and find out split direction/ratio
18845
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18846
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18847
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18848
0
        {
18849
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18850
0
            ImGuiDockPreviewData split_inner;
18851
0
            ImGuiDockPreviewData split_outer;
18852
0
            ImGuiDockPreviewData* split_data = &split_inner;
18853
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18854
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18855
0
                {
18856
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18857
0
                    if (split_outer.IsSplitDirExplicit)
18858
0
                        split_data = &split_outer;
18859
0
                }
18860
0
            if (!node || node->IsLeafNode())
18861
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18862
0
            if (split_data == &split_outer)
18863
0
                split_inner.IsDropAllowed = false;
18864
18865
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18866
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18867
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18868
18869
            // Queue docking request
18870
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18871
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18872
0
        }
18873
0
    }
18874
0
    EndDragDropTarget();
18875
0
}
18876
18877
//-----------------------------------------------------------------------------
18878
// Docking: Settings
18879
//-----------------------------------------------------------------------------
18880
// - DockSettingsRenameNodeReferences()
18881
// - DockSettingsRemoveNodeReferences()
18882
// - DockSettingsFindNodeSettings()
18883
// - DockSettingsHandler_ApplyAll()
18884
// - DockSettingsHandler_ReadOpen()
18885
// - DockSettingsHandler_ReadLine()
18886
// - DockSettingsHandler_DockNodeToSettings()
18887
// - DockSettingsHandler_WriteAll()
18888
//-----------------------------------------------------------------------------
18889
18890
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18891
0
{
18892
0
    ImGuiContext& g = *GImGui;
18893
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18894
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18895
0
    {
18896
0
        ImGuiWindow* window = g.Windows[window_n];
18897
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18898
0
            window->DockId = new_node_id;
18899
0
    }
18900
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18901
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18902
0
        if (settings->DockId == old_node_id)
18903
0
            settings->DockId = new_node_id;
18904
0
}
18905
18906
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18907
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18908
0
{
18909
0
    ImGuiContext& g = *GImGui;
18910
0
    int found = 0;
18911
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18912
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18913
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18914
0
            if (settings->DockId == node_ids[node_n])
18915
0
            {
18916
0
                settings->DockId = 0;
18917
0
                settings->DockOrder = -1;
18918
0
                if (++found < node_ids_count)
18919
0
                    break;
18920
0
                return;
18921
0
            }
18922
0
}
18923
18924
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18925
0
{
18926
    // FIXME-OPT
18927
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18928
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18929
0
        if (dc->NodesSettings[n].ID == id)
18930
0
            return &dc->NodesSettings[n];
18931
0
    return NULL;
18932
0
}
18933
18934
// Clear settings data
18935
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18936
0
{
18937
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18938
0
    dc->NodesSettings.clear();
18939
0
    DockContextClearNodes(ctx, 0, true);
18940
0
}
18941
18942
// Recreate nodes based on settings data
18943
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18944
0
{
18945
    // Prune settings at boot time only
18946
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18947
0
    if (ctx->Windows.Size == 0)
18948
0
        DockContextPruneUnusedSettingsNodes(ctx);
18949
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18950
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18951
0
}
18952
18953
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18954
0
{
18955
0
    if (strcmp(name, "Data") != 0)
18956
0
        return NULL;
18957
0
    return (void*)1;
18958
0
}
18959
18960
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18961
0
{
18962
0
    char c = 0;
18963
0
    int x = 0, y = 0;
18964
0
    int r = 0;
18965
18966
    // Parsing, e.g.
18967
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18968
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18969
    // Important: this code expect currently fields in a fixed order.
18970
0
    ImGuiDockNodeSettings node;
18971
0
    line = ImStrSkipBlank(line);
18972
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18973
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18974
0
    else return;
18975
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18976
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18977
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18978
0
    if (node.ParentNodeId == 0)
18979
0
    {
18980
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18981
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18982
0
    }
18983
0
    else
18984
0
    {
18985
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18986
0
    }
18987
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18988
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18989
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18990
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18991
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18992
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18993
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18994
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18995
0
    if (node.ParentNodeId != 0)
18996
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18997
0
            node.Depth = parent_settings->Depth + 1;
18998
0
    ctx->DockContext.NodesSettings.push_back(node);
18999
0
}
19000
19001
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19002
0
{
19003
0
    ImGuiDockNodeSettings node_settings;
19004
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19005
0
    node_settings.ID = node->ID;
19006
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19007
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19008
0
    node_settings.SelectedTabId = node->SelectedTabId;
19009
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19010
0
    node_settings.Depth = (char)depth;
19011
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19012
0
    node_settings.Pos = ImVec2ih(node->Pos);
19013
0
    node_settings.Size = ImVec2ih(node->Size);
19014
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19015
0
    dc->NodesSettings.push_back(node_settings);
19016
0
    if (node->ChildNodes[0])
19017
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19018
0
    if (node->ChildNodes[1])
19019
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19020
0
}
19021
19022
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19023
0
{
19024
0
    ImGuiContext& g = *ctx;
19025
0
    ImGuiDockContext* dc = &ctx->DockContext;
19026
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19027
0
        return;
19028
19029
    // Gather settings data
19030
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19031
0
    dc->NodesSettings.resize(0);
19032
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19033
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19034
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19035
0
            if (node->IsRootNode())
19036
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19037
19038
0
    int max_depth = 0;
19039
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19040
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19041
19042
    // Write to text buffer
19043
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19044
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19045
0
    {
19046
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19047
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19048
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19049
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19050
0
        if (node_settings->ParentNodeId)
19051
0
        {
19052
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19053
0
        }
19054
0
        else
19055
0
        {
19056
0
            if (node_settings->ParentWindowId)
19057
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19058
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19059
0
        }
19060
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19061
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19062
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19063
0
            buf->appendf(" NoResize=1");
19064
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19065
0
            buf->appendf(" CentralNode=1");
19066
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19067
0
            buf->appendf(" NoTabBar=1");
19068
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19069
0
            buf->appendf(" HiddenTabBar=1");
19070
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19071
0
            buf->appendf(" NoWindowMenuButton=1");
19072
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19073
0
            buf->appendf(" NoCloseButton=1");
19074
0
        if (node_settings->SelectedTabId)
19075
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19076
19077
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19078
0
        if (g.IO.ConfigDebugIniSettings)
19079
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19080
0
            {
19081
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19082
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19083
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19084
                // Iterate settings so we can give info about windows that didn't exist during the session.
19085
0
                int contains_window = 0;
19086
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19087
0
                    if (settings->DockId == node_settings->ID)
19088
0
                    {
19089
0
                        if (contains_window++ == 0)
19090
0
                            buf->appendf(" ; contains ");
19091
0
                        buf->appendf("'%s' ", settings->GetName());
19092
0
                    }
19093
0
            }
19094
19095
0
        buf->appendf("\n");
19096
0
    }
19097
0
    buf->appendf("\n");
19098
0
}
19099
19100
19101
//-----------------------------------------------------------------------------
19102
// [SECTION] PLATFORM DEPENDENT HELPERS
19103
//-----------------------------------------------------------------------------
19104
19105
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19106
19107
#ifdef _MSC_VER
19108
#pragma comment(lib, "user32")
19109
#pragma comment(lib, "kernel32")
19110
#endif
19111
19112
// Win32 clipboard implementation
19113
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19114
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19115
{
19116
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19117
    g.ClipboardHandlerData.clear();
19118
    if (!::OpenClipboard(NULL))
19119
        return NULL;
19120
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19121
    if (wbuf_handle == NULL)
19122
    {
19123
        ::CloseClipboard();
19124
        return NULL;
19125
    }
19126
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19127
    {
19128
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19129
        g.ClipboardHandlerData.resize(buf_len);
19130
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19131
    }
19132
    ::GlobalUnlock(wbuf_handle);
19133
    ::CloseClipboard();
19134
    return g.ClipboardHandlerData.Data;
19135
}
19136
19137
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19138
{
19139
    if (!::OpenClipboard(NULL))
19140
        return;
19141
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19142
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19143
    if (wbuf_handle == NULL)
19144
    {
19145
        ::CloseClipboard();
19146
        return;
19147
    }
19148
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19149
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19150
    ::GlobalUnlock(wbuf_handle);
19151
    ::EmptyClipboard();
19152
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19153
        ::GlobalFree(wbuf_handle);
19154
    ::CloseClipboard();
19155
}
19156
19157
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19158
19159
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19160
static PasteboardRef main_clipboard = 0;
19161
19162
// OSX clipboard implementation
19163
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19164
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19165
{
19166
    if (!main_clipboard)
19167
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19168
    PasteboardClear(main_clipboard);
19169
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19170
    if (cf_data)
19171
    {
19172
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19173
        CFRelease(cf_data);
19174
    }
19175
}
19176
19177
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19178
{
19179
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19180
    if (!main_clipboard)
19181
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19182
    PasteboardSynchronize(main_clipboard);
19183
19184
    ItemCount item_count = 0;
19185
    PasteboardGetItemCount(main_clipboard, &item_count);
19186
    for (ItemCount i = 0; i < item_count; i++)
19187
    {
19188
        PasteboardItemID item_id = 0;
19189
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19190
        CFArrayRef flavor_type_array = 0;
19191
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19192
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19193
        {
19194
            CFDataRef cf_data;
19195
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19196
            {
19197
                g.ClipboardHandlerData.clear();
19198
                int length = (int)CFDataGetLength(cf_data);
19199
                g.ClipboardHandlerData.resize(length + 1);
19200
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19201
                g.ClipboardHandlerData[length] = 0;
19202
                CFRelease(cf_data);
19203
                return g.ClipboardHandlerData.Data;
19204
            }
19205
        }
19206
    }
19207
    return NULL;
19208
}
19209
19210
#else
19211
19212
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19213
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19214
0
{
19215
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19216
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19217
0
}
19218
19219
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19220
0
{
19221
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19222
0
    g.ClipboardHandlerData.clear();
19223
0
    const char* text_end = text + strlen(text);
19224
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19225
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19226
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19227
0
}
19228
19229
#endif
19230
19231
// Win32 API IME support (for Asian languages, etc.)
19232
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19233
19234
#include <imm.h>
19235
#ifdef _MSC_VER
19236
#pragma comment(lib, "imm32")
19237
#endif
19238
19239
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19240
{
19241
    // Notify OS Input Method Editor of text input position
19242
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19243
    if (hwnd == 0)
19244
        return;
19245
19246
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19247
    if (HIMC himc = ::ImmGetContext(hwnd))
19248
    {
19249
        COMPOSITIONFORM composition_form = {};
19250
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19251
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19252
        composition_form.dwStyle = CFS_FORCE_POSITION;
19253
        ::ImmSetCompositionWindow(himc, &composition_form);
19254
        CANDIDATEFORM candidate_form = {};
19255
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19256
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19257
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19258
        ::ImmSetCandidateWindow(himc, &candidate_form);
19259
        ::ImmReleaseContext(hwnd, himc);
19260
    }
19261
}
19262
19263
#else
19264
19265
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19266
19267
#endif
19268
19269
//-----------------------------------------------------------------------------
19270
// [SECTION] METRICS/DEBUGGER WINDOW
19271
//-----------------------------------------------------------------------------
19272
// - RenderViewportThumbnail() [Internal]
19273
// - RenderViewportsThumbnails() [Internal]
19274
// - DebugTextEncoding()
19275
// - MetricsHelpMarker() [Internal]
19276
// - ShowFontAtlas() [Internal]
19277
// - ShowMetricsWindow()
19278
// - DebugNodeColumns() [Internal]
19279
// - DebugNodeDockNode() [Internal]
19280
// - DebugNodeDrawList() [Internal]
19281
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19282
// - DebugNodeFont() [Internal]
19283
// - DebugNodeFontGlyph() [Internal]
19284
// - DebugNodeStorage() [Internal]
19285
// - DebugNodeTabBar() [Internal]
19286
// - DebugNodeViewport() [Internal]
19287
// - DebugNodeWindow() [Internal]
19288
// - DebugNodeWindowSettings() [Internal]
19289
// - DebugNodeWindowsList() [Internal]
19290
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19291
//-----------------------------------------------------------------------------
19292
19293
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19294
19295
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19296
0
{
19297
0
    ImGuiContext& g = *GImGui;
19298
0
    ImGuiWindow* window = g.CurrentWindow;
19299
19300
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19301
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19302
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19303
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19304
0
    for (ImGuiWindow* thumb_window : g.Windows)
19305
0
    {
19306
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19307
0
            continue;
19308
0
        if (thumb_window->Viewport != viewport)
19309
0
            continue;
19310
19311
0
        ImRect thumb_r = thumb_window->Rect();
19312
0
        ImRect title_r = thumb_window->TitleBarRect();
19313
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
19314
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
19315
0
        thumb_r.ClipWithFull(bb);
19316
0
        title_r.ClipWithFull(bb);
19317
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19318
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19319
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19320
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19321
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19322
0
    }
19323
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19324
0
}
19325
19326
static void RenderViewportsThumbnails()
19327
0
{
19328
0
    ImGuiContext& g = *GImGui;
19329
0
    ImGuiWindow* window = g.CurrentWindow;
19330
19331
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
19332
0
    float SCALE = 1.0f / 8.0f;
19333
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19334
0
    for (ImGuiViewportP* viewport : g.Viewports)
19335
0
        bb_full.Add(viewport->GetMainRect());
19336
0
    ImVec2 p = window->DC.CursorPos;
19337
0
    ImVec2 off = p - bb_full.Min * SCALE;
19338
0
    for (ImGuiViewportP* viewport : g.Viewports)
19339
0
    {
19340
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19341
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19342
0
    }
19343
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19344
0
}
19345
19346
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19347
0
{
19348
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19349
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19350
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19351
0
}
19352
19353
// Draw an arbitrary US keyboard layout to visualize translated keys
19354
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19355
0
{
19356
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
19357
0
    const float  key_rounding = 3.0f;
19358
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
19359
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
19360
0
    const float  key_face_rounding = 2.0f;
19361
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
19362
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19363
0
    const float  key_row_offset = 9.0f;
19364
19365
0
    ImVec2 board_min = GetCursorScreenPos();
19366
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19367
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19368
19369
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19370
0
    const KeyLayoutData keys_to_display[] =
19371
0
    {
19372
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19373
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19374
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19375
0
    };
19376
19377
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19378
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19379
0
    Dummy(board_max - board_min);
19380
0
    if (!IsItemVisible())
19381
0
        return;
19382
0
    draw_list->PushClipRect(board_min, board_max, true);
19383
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19384
0
    {
19385
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19386
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19387
0
        ImVec2 key_max = key_min + key_size;
19388
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19389
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19390
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19391
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19392
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19393
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19394
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19395
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19396
0
        if (IsKeyDown(key_data->Key))
19397
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19398
0
    }
19399
0
    draw_list->PopClipRect();
19400
0
}
19401
19402
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19403
void ImGui::DebugTextEncoding(const char* str)
19404
0
{
19405
0
    Text("Text: \"%s\"", str);
19406
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19407
0
        return;
19408
0
    TableSetupColumn("Offset");
19409
0
    TableSetupColumn("UTF-8");
19410
0
    TableSetupColumn("Glyph");
19411
0
    TableSetupColumn("Codepoint");
19412
0
    TableHeadersRow();
19413
0
    for (const char* p = str; *p != 0; )
19414
0
    {
19415
0
        unsigned int c;
19416
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19417
0
        TableNextColumn();
19418
0
        Text("%d", (int)(p - str));
19419
0
        TableNextColumn();
19420
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19421
0
        {
19422
0
            if (byte_index > 0)
19423
0
                SameLine();
19424
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19425
0
        }
19426
0
        TableNextColumn();
19427
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19428
0
            TextUnformatted(p, p + c_utf8_len);
19429
0
        else
19430
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19431
0
        TableNextColumn();
19432
0
        Text("U+%04X", (int)c);
19433
0
        p += c_utf8_len;
19434
0
    }
19435
0
    EndTable();
19436
0
}
19437
19438
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19439
static void MetricsHelpMarker(const char* desc)
19440
0
{
19441
0
    ImGui::TextDisabled("(?)");
19442
0
    if (ImGui::BeginItemTooltip())
19443
0
    {
19444
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19445
0
        ImGui::TextUnformatted(desc);
19446
0
        ImGui::PopTextWrapPos();
19447
0
        ImGui::EndTooltip();
19448
0
    }
19449
0
}
19450
19451
// [DEBUG] List fonts in a font atlas and display its texture
19452
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19453
0
{
19454
0
    for (ImFont* font : atlas->Fonts)
19455
0
    {
19456
0
        PushID(font);
19457
0
        DebugNodeFont(font);
19458
0
        PopID();
19459
0
    }
19460
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19461
0
    {
19462
0
        ImGuiContext& g = *GImGui;
19463
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19464
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19465
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19466
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19467
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19468
0
        TreePop();
19469
0
    }
19470
0
}
19471
19472
void ImGui::ShowMetricsWindow(bool* p_open)
19473
0
{
19474
0
    ImGuiContext& g = *GImGui;
19475
0
    ImGuiIO& io = g.IO;
19476
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19477
0
    if (cfg->ShowDebugLog)
19478
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19479
0
    if (cfg->ShowIDStackTool)
19480
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19481
19482
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19483
0
    {
19484
0
        End();
19485
0
        return;
19486
0
    }
19487
19488
    // Basic info
19489
0
    Text("Dear ImGui %s", GetVersion());
19490
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19491
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19492
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19493
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19494
19495
0
    Separator();
19496
19497
    // Debugging enums
19498
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19499
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19500
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19501
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19502
0
    if (cfg->ShowWindowsRectsType < 0)
19503
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19504
0
    if (cfg->ShowTablesRectsType < 0)
19505
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19506
19507
0
    struct Funcs
19508
0
    {
19509
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19510
0
        {
19511
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19512
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19513
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19514
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19515
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19516
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19517
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19518
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19519
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19520
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19521
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
19522
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
19523
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19524
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19525
0
            IM_ASSERT(0);
19526
0
            return ImRect();
19527
0
        }
19528
19529
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19530
0
        {
19531
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19532
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19533
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19534
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19535
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19536
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19537
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19538
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19539
0
            IM_ASSERT(0);
19540
0
            return ImRect();
19541
0
        }
19542
0
    };
19543
19544
    // Tools
19545
0
    if (TreeNode("Tools"))
19546
0
    {
19547
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19548
0
        SameLine();
19549
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19550
0
        if (show_encoding_viewer)
19551
0
        {
19552
0
            static char buf[100] = "";
19553
0
            SetNextItemWidth(-FLT_MIN);
19554
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19555
0
            if (buf[0] != 0)
19556
0
                DebugTextEncoding(buf);
19557
0
            TreePop();
19558
0
        }
19559
19560
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19561
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19562
0
            DebugStartItemPicker();
19563
0
        SameLine();
19564
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19565
19566
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19567
0
        SameLine();
19568
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19569
19570
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
19571
0
        SameLine();
19572
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
19573
19574
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19575
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19576
0
        SameLine();
19577
0
        SetNextItemWidth(GetFontSize() * 12);
19578
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19579
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19580
0
        {
19581
0
            BulletText("'%s':", g.NavWindow->Name);
19582
0
            Indent();
19583
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19584
0
            {
19585
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19586
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19587
0
            }
19588
0
            Unindent();
19589
0
        }
19590
19591
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19592
0
        SameLine();
19593
0
        SetNextItemWidth(GetFontSize() * 12);
19594
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19595
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19596
0
        {
19597
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19598
0
            {
19599
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19600
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19601
0
                    continue;
19602
19603
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19604
0
                if (IsItemHovered())
19605
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19606
0
                Indent();
19607
0
                char buf[128];
19608
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19609
0
                {
19610
0
                    if (rect_n >= TRT_ColumnsRect)
19611
0
                    {
19612
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19613
0
                            continue;
19614
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19615
0
                        {
19616
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19617
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19618
0
                            Selectable(buf);
19619
0
                            if (IsItemHovered())
19620
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19621
0
                        }
19622
0
                    }
19623
0
                    else
19624
0
                    {
19625
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19626
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19627
0
                        Selectable(buf);
19628
0
                        if (IsItemHovered())
19629
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19630
0
                    }
19631
0
                }
19632
0
                Unindent();
19633
0
            }
19634
0
        }
19635
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
19636
19637
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19638
0
        SameLine();
19639
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19640
19641
0
        TreePop();
19642
0
    }
19643
19644
    // Windows
19645
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19646
0
    {
19647
        //SetNextItemOpen(true, ImGuiCond_Once);
19648
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19649
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19650
0
        if (TreeNode("By submission order (begin stack)"))
19651
0
        {
19652
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19653
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19654
0
            temp_buffer.resize(0);
19655
0
            for (ImGuiWindow* window : g.Windows)
19656
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
19657
0
                    temp_buffer.push_back(window);
19658
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19659
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19660
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19661
0
            TreePop();
19662
0
        }
19663
19664
0
        TreePop();
19665
0
    }
19666
19667
    // DrawLists
19668
0
    int drawlist_count = 0;
19669
0
    for (ImGuiViewportP* viewport : g.Viewports)
19670
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
19671
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19672
0
    {
19673
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19674
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19675
0
        for (ImGuiViewportP* viewport : g.Viewports)
19676
0
        {
19677
0
            bool viewport_has_drawlist = false;
19678
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
19679
0
            {
19680
0
                if (!viewport_has_drawlist)
19681
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19682
0
                viewport_has_drawlist = true;
19683
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
19684
0
            }
19685
0
        }
19686
0
        TreePop();
19687
0
    }
19688
19689
    // Viewports
19690
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19691
0
    {
19692
0
        Indent(GetTreeNodeToLabelSpacing());
19693
0
        RenderViewportsThumbnails();
19694
0
        Unindent(GetTreeNodeToLabelSpacing());
19695
19696
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19697
0
        SameLine();
19698
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19699
0
        if (open)
19700
0
        {
19701
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19702
0
            {
19703
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19704
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19705
0
                    i, mon.DpiScale * 100.0f,
19706
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19707
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19708
0
            }
19709
0
            TreePop();
19710
0
        }
19711
19712
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19713
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19714
0
        {
19715
0
            static ImVector<ImGuiViewportP*> viewports;
19716
0
            viewports.resize(g.Viewports.Size);
19717
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19718
0
            if (viewports.Size > 1)
19719
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19720
0
            for (ImGuiViewportP* viewport : viewports)
19721
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19722
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19723
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19724
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19725
0
            TreePop();
19726
0
        }
19727
0
        for (ImGuiViewportP* viewport : g.Viewports)
19728
0
            DebugNodeViewport(viewport);
19729
0
        TreePop();
19730
0
    }
19731
19732
    // Details for Popups
19733
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19734
0
    {
19735
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
19736
0
        {
19737
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19738
0
            ImGuiWindow* window = popup_data.Window;
19739
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19740
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19741
0
                popup_data.BackupNavWindow ? popup_data.BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19742
0
        }
19743
0
        TreePop();
19744
0
    }
19745
19746
    // Details for TabBars
19747
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19748
0
    {
19749
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19750
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19751
0
            {
19752
0
                PushID(tab_bar);
19753
0
                DebugNodeTabBar(tab_bar, "TabBar");
19754
0
                PopID();
19755
0
            }
19756
0
        TreePop();
19757
0
    }
19758
19759
    // Details for Tables
19760
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19761
0
    {
19762
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19763
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19764
0
                DebugNodeTable(table);
19765
0
        TreePop();
19766
0
    }
19767
19768
    // Details for Fonts
19769
0
    ImFontAtlas* atlas = g.IO.Fonts;
19770
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19771
0
    {
19772
0
        ShowFontAtlas(atlas);
19773
0
        TreePop();
19774
0
    }
19775
19776
    // Details for InputText
19777
0
    if (TreeNode("InputText"))
19778
0
    {
19779
0
        DebugNodeInputTextState(&g.InputTextState);
19780
0
        TreePop();
19781
0
    }
19782
19783
    // Details for TypingSelect
19784
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
19785
0
    {
19786
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
19787
0
        TreePop();
19788
0
    }
19789
19790
    // Details for Docking
19791
0
#ifdef IMGUI_HAS_DOCK
19792
0
    if (TreeNode("Docking"))
19793
0
    {
19794
0
        static bool root_nodes_only = true;
19795
0
        ImGuiDockContext* dc = &g.DockContext;
19796
0
        Checkbox("List root nodes", &root_nodes_only);
19797
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19798
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19799
0
        SameLine();
19800
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19801
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19802
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19803
0
                if (!root_nodes_only || node->IsRootNode())
19804
0
                    DebugNodeDockNode(node, "Node");
19805
0
        TreePop();
19806
0
    }
19807
0
#endif // #ifdef IMGUI_HAS_DOCK
19808
19809
    // Settings
19810
0
    if (TreeNode("Settings"))
19811
0
    {
19812
0
        if (SmallButton("Clear"))
19813
0
            ClearIniSettings();
19814
0
        SameLine();
19815
0
        if (SmallButton("Save to memory"))
19816
0
            SaveIniSettingsToMemory();
19817
0
        SameLine();
19818
0
        if (SmallButton("Save to disk"))
19819
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19820
0
        SameLine();
19821
0
        if (g.IO.IniFilename)
19822
0
            Text("\"%s\"", g.IO.IniFilename);
19823
0
        else
19824
0
            TextUnformatted("<NULL>");
19825
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
19826
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19827
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19828
0
        {
19829
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
19830
0
                BulletText("\"%s\"", handler.TypeName);
19831
0
            TreePop();
19832
0
        }
19833
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19834
0
        {
19835
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19836
0
                DebugNodeWindowSettings(settings);
19837
0
            TreePop();
19838
0
        }
19839
19840
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19841
0
        {
19842
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19843
0
                DebugNodeTableSettings(settings);
19844
0
            TreePop();
19845
0
        }
19846
19847
0
#ifdef IMGUI_HAS_DOCK
19848
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19849
0
        {
19850
0
            ImGuiDockContext* dc = &g.DockContext;
19851
0
            Text("In SettingsWindows:");
19852
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19853
0
                if (settings->DockId != 0)
19854
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
19855
0
            Text("In SettingsNodes:");
19856
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19857
0
            {
19858
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19859
0
                const char* selected_tab_name = NULL;
19860
0
                if (settings->SelectedTabId)
19861
0
                {
19862
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19863
0
                        selected_tab_name = window->Name;
19864
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19865
0
                        selected_tab_name = window_settings->GetName();
19866
0
                }
19867
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19868
0
            }
19869
0
            TreePop();
19870
0
        }
19871
0
#endif // #ifdef IMGUI_HAS_DOCK
19872
19873
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19874
0
        {
19875
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19876
0
            TreePop();
19877
0
        }
19878
0
        TreePop();
19879
0
    }
19880
19881
    // Settings
19882
0
    if (TreeNode("Memory allocations"))
19883
0
    {
19884
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
19885
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
19886
0
        Text("Recent frames with allocations:");
19887
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
19888
0
        for (int n = buf_size - 1; n >= 0; n--)
19889
0
        {
19890
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
19891
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
19892
0
        }
19893
0
        TreePop();
19894
0
    }
19895
19896
0
    if (TreeNode("Inputs"))
19897
0
    {
19898
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19899
0
        {
19900
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19901
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19902
0
            Indent();
19903
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19904
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19905
#else
19906
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19907
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19908
#endif
19909
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19910
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19911
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19912
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19913
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19914
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19915
0
            Unindent();
19916
0
        }
19917
19918
0
        Text("MOUSE STATE");
19919
0
        {
19920
0
            Indent();
19921
0
            if (IsMousePosValid())
19922
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19923
0
            else
19924
0
                Text("Mouse pos: <INVALID>");
19925
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19926
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19927
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19928
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19929
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19930
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19931
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
19932
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19933
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19934
0
            Unindent();
19935
0
        }
19936
19937
0
        Text("MOUSE WHEELING");
19938
0
        {
19939
0
            Indent();
19940
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19941
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19942
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19943
0
            Unindent();
19944
0
        }
19945
19946
0
        Text("KEY OWNERS");
19947
0
        {
19948
0
            Indent();
19949
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19950
0
            {
19951
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19952
0
                {
19953
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19954
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19955
0
                        continue;
19956
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19957
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19958
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19959
0
                }
19960
0
                EndListBox();
19961
0
            }
19962
0
            Unindent();
19963
0
        }
19964
0
        Text("SHORTCUT ROUTING");
19965
0
        {
19966
0
            Indent();
19967
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19968
0
            {
19969
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19970
0
                {
19971
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19972
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19973
0
                    {
19974
0
                        char key_chord_name[64];
19975
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19976
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19977
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19978
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19979
0
                        idx = routing_data->NextEntryIndex;
19980
0
                    }
19981
0
                }
19982
0
                EndListBox();
19983
0
            }
19984
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19985
0
            Unindent();
19986
0
        }
19987
0
        TreePop();
19988
0
    }
19989
19990
0
    if (TreeNode("Internal state"))
19991
0
    {
19992
0
        Text("WINDOWING");
19993
0
        Indent();
19994
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19995
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19996
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19997
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19998
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19999
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20000
0
        Unindent();
20001
20002
0
        Text("ITEMS");
20003
0
        Indent();
20004
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20005
0
        DebugLocateItemOnHover(g.ActiveId);
20006
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20007
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20008
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20009
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20010
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20011
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20012
0
        Unindent();
20013
20014
0
        Text("NAV,FOCUS");
20015
0
        Indent();
20016
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20017
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20018
0
        DebugLocateItemOnHover(g.NavId);
20019
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20020
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20021
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20022
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20023
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20024
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20025
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20026
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20027
0
        Unindent();
20028
20029
0
        TreePop();
20030
0
    }
20031
20032
    // Overlay: Display windows Rectangles and Begin Order
20033
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20034
0
    {
20035
0
        for (ImGuiWindow* window : g.Windows)
20036
0
        {
20037
0
            if (!window->WasActive)
20038
0
                continue;
20039
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20040
0
            if (cfg->ShowWindowsRects)
20041
0
            {
20042
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20043
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20044
0
            }
20045
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20046
0
            {
20047
0
                char buf[32];
20048
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20049
0
                float font_size = GetFontSize();
20050
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20051
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20052
0
            }
20053
0
        }
20054
0
    }
20055
20056
    // Overlay: Display Tables Rectangles
20057
0
    if (cfg->ShowTablesRects)
20058
0
    {
20059
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20060
0
        {
20061
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20062
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20063
0
                continue;
20064
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20065
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20066
0
            {
20067
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20068
0
                {
20069
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20070
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20071
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20072
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20073
0
                }
20074
0
            }
20075
0
            else
20076
0
            {
20077
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20078
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20079
0
            }
20080
0
        }
20081
0
    }
20082
20083
0
#ifdef IMGUI_HAS_DOCK
20084
    // Overlay: Display Docking info
20085
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20086
0
    {
20087
0
        char buf[64] = "";
20088
0
        char* p = buf;
20089
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20090
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20091
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20092
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20093
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20094
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20095
0
        int depth = DockNodeGetDepth(node);
20096
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20097
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20098
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20099
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20100
0
    }
20101
0
#endif // #ifdef IMGUI_HAS_DOCK
20102
20103
0
    End();
20104
0
}
20105
20106
// [DEBUG] Display contents of Columns
20107
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20108
0
{
20109
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20110
0
        return;
20111
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20112
0
    for (ImGuiOldColumnData& column : columns->Columns)
20113
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20114
0
    TreePop();
20115
0
}
20116
20117
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20118
0
{
20119
0
    using namespace ImGui;
20120
0
    PushID(label);
20121
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20122
0
    Text("%s:", label);
20123
0
    if (!enabled)
20124
0
        BeginDisabled();
20125
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20126
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20127
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20128
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20129
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20130
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20131
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20132
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20133
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20134
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20135
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20136
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20137
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20138
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20139
0
    if (!enabled)
20140
0
        EndDisabled();
20141
0
    PopStyleVar();
20142
0
    PopID();
20143
0
}
20144
20145
// [DEBUG] Display contents of ImDockNode
20146
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20147
0
{
20148
0
    ImGuiContext& g = *GImGui;
20149
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20150
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
20151
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20152
0
    bool open;
20153
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20154
0
    if (node->Windows.Size > 0)
20155
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20156
0
    else
20157
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20158
0
    if (!is_alive) { PopStyleColor(); }
20159
0
    if (is_active && IsItemHovered())
20160
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20161
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20162
0
    if (open)
20163
0
    {
20164
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20165
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20166
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20167
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20168
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
20169
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20170
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20171
0
        BulletText("Misc:%s%s%s%s%s%s%s",
20172
0
            node->IsDockSpace() ? " IsDockSpace" : "",
20173
0
            node->IsCentralNode() ? " IsCentralNode" : "",
20174
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20175
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20176
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20177
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20178
0
        {
20179
0
            if (BeginTable("flags", 4))
20180
0
            {
20181
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20182
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20183
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20184
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20185
0
                EndTable();
20186
0
            }
20187
0
            TreePop();
20188
0
        }
20189
0
        if (node->ParentNode)
20190
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
20191
0
        if (node->ChildNodes[0])
20192
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20193
0
        if (node->ChildNodes[1])
20194
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20195
0
        if (node->TabBar)
20196
0
            DebugNodeTabBar(node->TabBar, "TabBar");
20197
0
        DebugNodeWindowsList(&node->Windows, "Windows");
20198
20199
0
        TreePop();
20200
0
    }
20201
0
}
20202
20203
// [DEBUG] Display contents of ImDrawList
20204
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20205
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20206
0
{
20207
0
    ImGuiContext& g = *GImGui;
20208
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20209
0
    int cmd_count = draw_list->CmdBuffer.Size;
20210
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20211
0
        cmd_count--;
20212
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20213
0
    if (draw_list == GetWindowDrawList())
20214
0
    {
20215
0
        SameLine();
20216
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20217
0
        if (node_open)
20218
0
            TreePop();
20219
0
        return;
20220
0
    }
20221
20222
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20223
0
    if (window && IsItemHovered() && fg_draw_list)
20224
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20225
0
    if (!node_open)
20226
0
        return;
20227
20228
0
    if (window && !window->WasActive)
20229
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20230
20231
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20232
0
    {
20233
0
        if (pcmd->UserCallback)
20234
0
        {
20235
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20236
0
            continue;
20237
0
        }
20238
20239
0
        char buf[300];
20240
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20241
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
20242
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20243
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20244
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20245
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20246
0
        if (!pcmd_node_open)
20247
0
            continue;
20248
20249
        // Calculate approximate coverage area (touched pixel count)
20250
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20251
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20252
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20253
0
        float total_area = 0.0f;
20254
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20255
0
        {
20256
0
            ImVec2 triangle[3];
20257
0
            for (int n = 0; n < 3; n++, idx_n++)
20258
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20259
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20260
0
        }
20261
20262
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20263
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20264
0
        Selectable(buf);
20265
0
        if (IsItemHovered() && fg_draw_list)
20266
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20267
20268
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20269
0
        ImGuiListClipper clipper;
20270
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20271
0
        while (clipper.Step())
20272
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20273
0
            {
20274
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20275
0
                ImVec2 triangle[3];
20276
0
                for (int n = 0; n < 3; n++, idx_i++)
20277
0
                {
20278
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20279
0
                    triangle[n] = v.pos;
20280
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20281
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20282
0
                }
20283
20284
0
                Selectable(buf, false);
20285
0
                if (fg_draw_list && IsItemHovered())
20286
0
                {
20287
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20288
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20289
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20290
0
                    fg_draw_list->Flags = backup_flags;
20291
0
                }
20292
0
            }
20293
0
        TreePop();
20294
0
    }
20295
0
    TreePop();
20296
0
}
20297
20298
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20299
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20300
0
{
20301
0
    IM_ASSERT(show_mesh || show_aabb);
20302
20303
    // Draw wire-frame version of all triangles
20304
0
    ImRect clip_rect = draw_cmd->ClipRect;
20305
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20306
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20307
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20308
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20309
0
    {
20310
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20311
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20312
20313
0
        ImVec2 triangle[3];
20314
0
        for (int n = 0; n < 3; n++, idx_n++)
20315
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20316
0
        if (show_mesh)
20317
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20318
0
    }
20319
    // Draw bounding boxes
20320
0
    if (show_aabb)
20321
0
    {
20322
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20323
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20324
0
    }
20325
0
    out_draw_list->Flags = backup_flags;
20326
0
}
20327
20328
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20329
void ImGui::DebugNodeFont(ImFont* font)
20330
0
{
20331
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20332
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20333
0
    SameLine();
20334
0
    if (SmallButton("Set as default"))
20335
0
        GetIO().FontDefault = font;
20336
0
    if (!opened)
20337
0
        return;
20338
20339
    // Display preview text
20340
0
    PushFont(font);
20341
0
    Text("The quick brown fox jumps over the lazy dog");
20342
0
    PopFont();
20343
20344
    // Display details
20345
0
    SetNextItemWidth(GetFontSize() * 8);
20346
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20347
0
    SameLine(); MetricsHelpMarker(
20348
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
20349
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20350
0
        "You may oversample them to get some flexibility with scaling. "
20351
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20352
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20353
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20354
0
    char c_str[5];
20355
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20356
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20357
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20358
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20359
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20360
0
        if (font->ConfigData)
20361
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20362
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20363
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20364
20365
    // Display all glyphs of the fonts in separate pages of 256 characters
20366
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20367
0
    {
20368
0
        ImDrawList* draw_list = GetWindowDrawList();
20369
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20370
0
        const float cell_size = font->FontSize * 1;
20371
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20372
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20373
0
        {
20374
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20375
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20376
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20377
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20378
0
            {
20379
0
                base += 4096 - 256;
20380
0
                continue;
20381
0
            }
20382
20383
0
            int count = 0;
20384
0
            for (unsigned int n = 0; n < 256; n++)
20385
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20386
0
                    count++;
20387
0
            if (count <= 0)
20388
0
                continue;
20389
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20390
0
                continue;
20391
20392
            // Draw a 16x16 grid of glyphs
20393
0
            ImVec2 base_pos = GetCursorScreenPos();
20394
0
            for (unsigned int n = 0; n < 256; n++)
20395
0
            {
20396
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20397
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20398
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20399
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20400
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20401
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20402
0
                if (!glyph)
20403
0
                    continue;
20404
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20405
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20406
0
                {
20407
0
                    DebugNodeFontGlyph(font, glyph);
20408
0
                    EndTooltip();
20409
0
                }
20410
0
            }
20411
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20412
0
            TreePop();
20413
0
        }
20414
0
        TreePop();
20415
0
    }
20416
0
    TreePop();
20417
0
}
20418
20419
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20420
0
{
20421
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20422
0
    Separator();
20423
0
    Text("Visible: %d", glyph->Visible);
20424
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20425
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20426
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20427
0
}
20428
20429
// [DEBUG] Display contents of ImGuiStorage
20430
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20431
0
{
20432
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20433
0
        return;
20434
0
    for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20435
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20436
0
    TreePop();
20437
0
}
20438
20439
// [DEBUG] Display contents of ImGuiTabBar
20440
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20441
0
{
20442
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20443
0
    char buf[256];
20444
0
    char* p = buf;
20445
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20446
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20447
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20448
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20449
0
    {
20450
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20451
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20452
0
    }
20453
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20454
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20455
0
    bool open = TreeNode(label, "%s", buf);
20456
0
    if (!is_active) { PopStyleColor(); }
20457
0
    if (is_active && IsItemHovered())
20458
0
    {
20459
0
        ImDrawList* draw_list = GetForegroundDrawList();
20460
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20461
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20462
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20463
0
    }
20464
0
    if (open)
20465
0
    {
20466
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20467
0
        {
20468
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20469
0
            PushID(tab);
20470
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20471
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20472
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20473
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20474
0
            PopID();
20475
0
        }
20476
0
        TreePop();
20477
0
    }
20478
0
}
20479
20480
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20481
0
{
20482
0
    SetNextItemOpen(true, ImGuiCond_Once);
20483
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20484
0
    {
20485
0
        ImGuiWindowFlags flags = viewport->Flags;
20486
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20487
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20488
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20489
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20490
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20491
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20492
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20493
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20494
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20495
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20496
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20497
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20498
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20499
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20500
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20501
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20502
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20503
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20504
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20505
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20506
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20507
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20508
0
        TreePop();
20509
0
    }
20510
0
}
20511
20512
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20513
0
{
20514
0
    if (window == NULL)
20515
0
    {
20516
0
        BulletText("%s: NULL", label);
20517
0
        return;
20518
0
    }
20519
20520
0
    ImGuiContext& g = *GImGui;
20521
0
    const bool is_active = window->WasActive;
20522
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20523
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20524
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20525
0
    if (!is_active) { PopStyleColor(); }
20526
0
    if (IsItemHovered() && is_active)
20527
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20528
0
    if (!open)
20529
0
        return;
20530
20531
0
    if (window->MemoryCompacted)
20532
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20533
20534
0
    ImGuiWindowFlags flags = window->Flags;
20535
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20536
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20537
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20538
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20539
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20540
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20541
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20542
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20543
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20544
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20545
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20546
0
    {
20547
0
        ImRect r = window->NavRectRel[layer];
20548
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20549
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20550
0
        else
20551
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20552
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20553
0
    }
20554
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20555
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20556
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20557
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20558
20559
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20560
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20561
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20562
0
    if (window->DockNode || window->DockNodeAsHost)
20563
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20564
20565
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20566
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20567
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20568
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20569
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20570
0
    {
20571
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
20572
0
            DebugNodeColumns(&columns);
20573
0
        TreePop();
20574
0
    }
20575
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20576
0
    TreePop();
20577
0
}
20578
20579
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20580
0
{
20581
0
    if (settings->WantDelete)
20582
0
        BeginDisabled();
20583
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20584
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20585
0
    if (settings->WantDelete)
20586
0
        EndDisabled();
20587
0
}
20588
20589
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20590
0
{
20591
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20592
0
        return;
20593
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20594
0
    {
20595
0
        PushID((*windows)[i]);
20596
0
        DebugNodeWindow((*windows)[i], "Window");
20597
0
        PopID();
20598
0
    }
20599
0
    TreePop();
20600
0
}
20601
20602
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20603
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20604
0
{
20605
0
    for (int i = 0; i < windows_size; i++)
20606
0
    {
20607
0
        ImGuiWindow* window = windows[i];
20608
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20609
0
            continue;
20610
0
        char buf[20];
20611
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20612
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20613
0
        DebugNodeWindow(window, buf);
20614
0
        Indent();
20615
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20616
0
        Unindent();
20617
0
    }
20618
0
}
20619
20620
//-----------------------------------------------------------------------------
20621
// [SECTION] DEBUG LOG WINDOW
20622
//-----------------------------------------------------------------------------
20623
20624
void ImGui::DebugLog(const char* fmt, ...)
20625
0
{
20626
0
    va_list args;
20627
0
    va_start(args, fmt);
20628
0
    DebugLogV(fmt, args);
20629
0
    va_end(args);
20630
0
}
20631
20632
void ImGui::DebugLogV(const char* fmt, va_list args)
20633
0
{
20634
0
    ImGuiContext& g = *GImGui;
20635
0
    const int old_size = g.DebugLogBuf.size();
20636
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20637
0
    g.DebugLogBuf.appendfv(fmt, args);
20638
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20639
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20640
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20641
#ifdef IMGUI_ENABLE_TEST_ENGINE
20642
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
20643
        IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
20644
#endif
20645
0
}
20646
20647
void ImGui::ShowDebugLogWindow(bool* p_open)
20648
0
{
20649
0
    ImGuiContext& g = *GImGui;
20650
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20651
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20652
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20653
0
    {
20654
0
        End();
20655
0
        return;
20656
0
    }
20657
20658
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20659
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20660
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20661
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20662
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20663
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20664
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20665
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20666
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20667
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20668
20669
0
    if (SmallButton("Clear"))
20670
0
    {
20671
0
        g.DebugLogBuf.clear();
20672
0
        g.DebugLogIndex.clear();
20673
0
    }
20674
0
    SameLine();
20675
0
    if (SmallButton("Copy"))
20676
0
        SetClipboardText(g.DebugLogBuf.c_str());
20677
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20678
20679
0
    ImGuiListClipper clipper;
20680
0
    clipper.Begin(g.DebugLogIndex.size());
20681
0
    while (clipper.Step())
20682
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20683
0
        {
20684
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20685
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20686
0
            TextUnformatted(line_begin, line_end);
20687
0
            ImRect text_rect = g.LastItemData.Rect;
20688
0
            if (IsItemHovered())
20689
0
                for (const char* p = line_begin; p <= line_end - 10; p++)
20690
0
                {
20691
0
                    ImGuiID id = 0;
20692
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20693
0
                        continue;
20694
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20695
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20696
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20697
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20698
0
                        DebugLocateItemOnHover(id);
20699
0
                    p += 10;
20700
0
                }
20701
0
        }
20702
0
    if (GetScrollY() >= GetScrollMaxY())
20703
0
        SetScrollHereY(1.0f);
20704
0
    EndChild();
20705
20706
0
    End();
20707
0
}
20708
20709
//-----------------------------------------------------------------------------
20710
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
20711
//-----------------------------------------------------------------------------
20712
20713
// Draw a small cross at current CursorPos in current window's DrawList
20714
void ImGui::DebugDrawCursorPos(ImU32 col)
20715
0
{
20716
0
    ImGuiContext& g = *GImGui;
20717
0
    ImGuiWindow* window = g.CurrentWindow;
20718
0
    ImVec2 pos = window->DC.CursorPos;
20719
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
20720
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
20721
0
}
20722
20723
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
20724
void ImGui::DebugDrawLineExtents(ImU32 col)
20725
0
{
20726
0
    ImGuiContext& g = *GImGui;
20727
0
    ImGuiWindow* window = g.CurrentWindow;
20728
0
    float curr_x = window->DC.CursorPos.x;
20729
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
20730
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
20731
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
20732
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
20733
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
20734
0
}
20735
20736
// Draw last item rect in ForegroundDrawList (so it is always visible)
20737
void ImGui::DebugDrawItemRect(ImU32 col)
20738
0
{
20739
0
    ImGuiContext& g = *GImGui;
20740
0
    ImGuiWindow* window = g.CurrentWindow;
20741
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
20742
0
}
20743
20744
// [DEBUG] Locate item position/rectangle given an ID.
20745
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20746
20747
void ImGui::DebugLocateItem(ImGuiID target_id)
20748
0
{
20749
0
    ImGuiContext& g = *GImGui;
20750
0
    g.DebugLocateId = target_id;
20751
0
    g.DebugLocateFrames = 2;
20752
0
}
20753
20754
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20755
0
{
20756
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20757
0
        return;
20758
0
    ImGuiContext& g = *GImGui;
20759
0
    DebugLocateItem(target_id);
20760
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20761
0
}
20762
20763
void ImGui::DebugLocateItemResolveWithLastItem()
20764
0
{
20765
0
    ImGuiContext& g = *GImGui;
20766
0
    ImGuiLastItemData item_data = g.LastItemData;
20767
0
    g.DebugLocateId = 0;
20768
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20769
0
    ImRect r = item_data.Rect;
20770
0
    r.Expand(3.0f);
20771
0
    ImVec2 p1 = g.IO.MousePos;
20772
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20773
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20774
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20775
0
}
20776
20777
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20778
void ImGui::UpdateDebugToolItemPicker()
20779
24.1k
{
20780
24.1k
    ImGuiContext& g = *GImGui;
20781
24.1k
    g.DebugItemPickerBreakId = 0;
20782
24.1k
    if (!g.DebugItemPickerActive)
20783
24.1k
        return;
20784
20785
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20786
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20787
0
    if (IsKeyPressed(ImGuiKey_Escape))
20788
0
        g.DebugItemPickerActive = false;
20789
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20790
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20791
0
    {
20792
0
        g.DebugItemPickerBreakId = hovered_id;
20793
0
        g.DebugItemPickerActive = false;
20794
0
    }
20795
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20796
0
        if (change_mapping && IsMouseClicked(mouse_button))
20797
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20798
0
    SetNextWindowBgAlpha(0.70f);
20799
0
    if (!BeginTooltip())
20800
0
        return;
20801
0
    Text("HoveredId: 0x%08X", hovered_id);
20802
0
    Text("Press ESC to abort picking.");
20803
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20804
0
    if (change_mapping)
20805
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20806
0
    else
20807
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20808
0
    EndTooltip();
20809
0
}
20810
20811
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
20812
void ImGui::UpdateDebugToolStackQueries()
20813
24.1k
{
20814
24.1k
    ImGuiContext& g = *GImGui;
20815
24.1k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20816
20817
    // Clear hook when id stack tool is not visible
20818
24.1k
    g.DebugHookIdInfo = 0;
20819
24.1k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20820
24.1k
        return;
20821
20822
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20823
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20824
2
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20825
2
    if (tool->QueryId != query_id)
20826
0
    {
20827
0
        tool->QueryId = query_id;
20828
0
        tool->StackLevel = -1;
20829
0
        tool->Results.resize(0);
20830
0
    }
20831
2
    if (query_id == 0)
20832
2
        return;
20833
20834
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20835
0
    int stack_level = tool->StackLevel;
20836
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20837
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20838
0
            tool->StackLevel++;
20839
20840
    // Update hook
20841
0
    stack_level = tool->StackLevel;
20842
0
    if (stack_level == -1)
20843
0
        g.DebugHookIdInfo = query_id;
20844
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20845
0
    {
20846
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20847
0
        tool->Results[stack_level].QueryFrameCount++;
20848
0
    }
20849
0
}
20850
20851
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
20852
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20853
0
{
20854
0
    ImGuiContext& g = *GImGui;
20855
0
    ImGuiWindow* window = g.CurrentWindow;
20856
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20857
20858
    // Step 0: stack query
20859
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20860
0
    if (tool->StackLevel == -1)
20861
0
    {
20862
0
        tool->StackLevel++;
20863
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20864
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20865
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20866
0
        return;
20867
0
    }
20868
20869
    // Step 1+: query for individual level
20870
0
    IM_ASSERT(tool->StackLevel >= 0);
20871
0
    if (tool->StackLevel != window->IDStack.Size)
20872
0
        return;
20873
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20874
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20875
20876
0
    switch (data_type)
20877
0
    {
20878
0
    case ImGuiDataType_S32:
20879
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20880
0
        break;
20881
0
    case ImGuiDataType_String:
20882
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20883
0
        break;
20884
0
    case ImGuiDataType_Pointer:
20885
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20886
0
        break;
20887
0
    case ImGuiDataType_ID:
20888
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20889
0
            return;
20890
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20891
0
        break;
20892
0
    default:
20893
0
        IM_ASSERT(0);
20894
0
    }
20895
0
    info->QuerySuccess = true;
20896
0
    info->DataType = data_type;
20897
0
}
20898
20899
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20900
0
{
20901
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20902
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20903
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20904
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20905
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20906
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20907
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20908
0
        return (*buf = 0);
20909
#ifdef IMGUI_ENABLE_TEST_ENGINE
20910
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20911
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20912
#endif
20913
0
    return ImFormatString(buf, buf_size, "???");
20914
0
}
20915
20916
// ID Stack Tool: Display UI
20917
void ImGui::ShowIDStackToolWindow(bool* p_open)
20918
0
{
20919
0
    ImGuiContext& g = *GImGui;
20920
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20921
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20922
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20923
0
    {
20924
0
        End();
20925
0
        return;
20926
0
    }
20927
20928
    // Display hovered/active status
20929
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20930
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20931
0
    const ImGuiID active_id = g.ActiveId;
20932
#ifdef IMGUI_ENABLE_TEST_ENGINE
20933
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20934
#else
20935
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20936
0
#endif
20937
0
    SameLine();
20938
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20939
20940
    // CTRL+C to copy path
20941
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20942
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20943
0
    SameLine();
20944
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20945
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20946
0
    {
20947
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20948
0
        char* p = g.TempBuffer.Data;
20949
0
        char* p_end = p + g.TempBuffer.Size;
20950
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20951
0
        {
20952
0
            *p++ = '/';
20953
0
            char level_desc[256];
20954
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20955
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20956
0
            {
20957
0
                if (level_desc[n] == '/')
20958
0
                    *p++ = '\\';
20959
0
                *p++ = level_desc[n];
20960
0
            }
20961
0
        }
20962
0
        *p = '\0';
20963
0
        SetClipboardText(g.TempBuffer.Data);
20964
0
    }
20965
20966
    // Display decorated stack
20967
0
    tool->LastActiveFrame = g.FrameCount;
20968
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20969
0
    {
20970
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20971
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20972
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20973
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20974
0
        TableHeadersRow();
20975
0
        for (int n = 0; n < tool->Results.Size; n++)
20976
0
        {
20977
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20978
0
            TableNextColumn();
20979
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20980
0
            TableNextColumn();
20981
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20982
0
            TextUnformatted(g.TempBuffer.Data);
20983
0
            TableNextColumn();
20984
0
            Text("0x%08X", info->ID);
20985
0
            if (n == tool->Results.Size - 1)
20986
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20987
0
        }
20988
0
        EndTable();
20989
0
    }
20990
0
    End();
20991
0
}
20992
20993
#else
20994
20995
void ImGui::ShowMetricsWindow(bool*) {}
20996
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20997
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20998
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20999
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21000
void ImGui::DebugNodeFont(ImFont*) {}
21001
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21002
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21003
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21004
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21005
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21006
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21007
21008
void ImGui::DebugLog(const char*, ...) {}
21009
void ImGui::DebugLogV(const char*, va_list) {}
21010
void ImGui::ShowDebugLogWindow(bool*) {}
21011
void ImGui::ShowIDStackToolWindow(bool*) {}
21012
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21013
void ImGui::UpdateDebugToolItemPicker() {}
21014
void ImGui::UpdateDebugToolStackQueries() {}
21015
21016
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21017
21018
//-----------------------------------------------------------------------------
21019
21020
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21021
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21022
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21023
#include "imgui_user.inl"
21024
#endif
21025
21026
//-----------------------------------------------------------------------------
21027
21028
#endif // #ifndef IMGUI_DISABLE